Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 691
krasilich Avatar asked Jan 06 '11 12:01

krasilich


People also ask

How to insert HTML content into an iframe using jQuery?

Answer: Use the jQuery contents() method You can use the jQuery contents() method in combination with the find() , val() and html() methods to insert text or HTML inside an iframe body.

How to get iframe body content in jQuery?

In jQuery, that would be $('#frame'). contents(). find('body') . Note that because of the same-origin policy, this will only work if the iframe and the surrounding pages' URLs have exactly the same hostname and port number.

How to add content into iframe using JavaScript?

ready(function() { var $doc = $("#iframe"). contentWindow. document; var $body = $("<body>"). text("Test"); $body.


1 Answers

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>
like image 87
sajjad hussain Avatar answered Oct 17 '22 23:10

sajjad hussain