3

I have a jQuery snippet as below:

$.ajax({
  ....
  success: function(myContent) {
    .....
    $('<iframe id="myFrame" name="myFrame">').appendTo('body').ready(function(){
      $('#myFrame').contents().find('body').append(myContent);
    });
    .....
  });
}); 

When the event is triggered at the first time, only an empty iframe displays, but if the event is triggered at the second time, content is appended into the iframe successfully. Any obvious error in this snippet?

3 Answers 3

12

I believe some browsers need a short delay for it to recognize the DOM of a new iframe. Using a timeout should work:

$('<iframe id="myFrame" name="myFrame">').appendTo("body").ready(function(){
    setTimeout(function(){
        $('#myFrame').contents().find('body').append(myContent);
    },50);
});
2
4

I think this is what you are looking for:

$('<iframe id="myFrame" name="myFrame">').appendTo('body');
$('iframe').contents().find('body').html(myContent);       

Demo: http://jsfiddle.net/vbNGA/1/

2
  • Hi codefOrmer, thank you for your answer, Adam's answer fixed my problem.
    – cnherald
    Commented Mar 2, 2012 at 11:06
  • 3
    @cnherald who is Adam?
    – dezman
    Commented Feb 26, 2014 at 23:40
1

This simple code may be use for you, it works fine for me.

$("#iframe_id").contents().find("body").append("Contents to display in iframe");

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.