jQuery add iFrame with content

krasilich picture krasilich · Jan 6, 2011 · Viewed 48.3k times · Source

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?

Answer

sajjad hussain picture sajjad hussain · Oct 29, 2011

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>