krasilich
krasilich

Reputation: 653

jQuery add iFrame with content

I've such a problem. I need to open iframe in fancybox (I require iframe because I need to browse through links in the opened document and stay in fancybox), but I want to put content into iframe from variable, not through src attribute (I've already got content by AJAX (I need to do some checks on content before putting it to iframe, so there are no way to do it instead of AJAX query), so I do not need one more query).

Fancybox does not allow to use 'content' attribute with 'type':'iframe'. So I decided to create iframe dynamically, insert my content into it, and show iframe by fancybox as a regular block.

It's like

jQuery('<iframe id="someId"/>').appendTo('body').contents().find('body').append(content);

And than

jQuery('<iframe id="someId"/>').fancybox();

But the first part does not work. I can see the iframe that was added to page but without any content (I have full HTML page in variable content, but when I try to append just some text it doesn't work as well).

What I've done wrong?

Maybe there is another way to do what I need?

Upvotes: 15

Views: 49804

Answers (3)

Igor Parra
Igor Parra

Reputation: 10348

Has passed time of this question, but here is another solution:

var ifrm = document.createElement("iframe");
document.body.appendChild(ifrm);
ifrm.id = "someId"; // optional id
ifrm.onload = function() {
    // optional onload behaviour
}
setTimeout(function() {
    $(ifrm).contents().find("body").html(content);
}, 1);

Upvotes: 2

sajjad hussain
sajjad hussain

Reputation: 181

your problem will be solve after calling jquery's ready method like this

<script type="text/javascript">
$(function(){
$('<iframe id="someId"/>').appendTo('body');
$('#someId').contents().find('body').append('<b>hello sajjad</b>');
});
</script>

<iframe id="someId"></iframe>

Upvotes: 18

Marcus Whybrow
Marcus Whybrow

Reputation: 19998

What happens if you split that line in two:

jQuery('<iframe id="someId"/>').appendTo('body');
jQuery('#someId').contents().find('body').append(content);

Then change your selector to be correct, before it was creating a new iframe, not inserting it in the DOM and the calling fancybox on it, however this should work:

jQuery('#someId').fancybox();

Upvotes: 4

Related Questions