jQuery: Set the content of an empty IFRAME

14 comments

I had to do some JS trickery to implement a preview feature by posting via AJAX without having to reload the current page.

The problem I ran into was displaying the output into an iframe.

Assuming the HTML is:

<iframe id='preview-iframe' src="about:blank"></iframe>

We can use this jQuery command to inject the HTML into the iframe.

$('#preview-iframe').contents().find('html').html(data);

Update (18/01/13): Thanks Nikri for the IE about:blank fix!

Sources

Related Posts

14 comments:

  1. This worked for me, but I had to load a page into the iframe first. Othewise, there was no html object for jquery to find and then fill.

    ReplyDelete
  2. Ahh good point, didn't spot that. Thanks!

    ReplyDelete
  3. Seems not to work on IE, right ?

    ReplyDelete
  4. Works beautifully! Thanks for this.

    ReplyDelete
  5. Hi Saam,

    Just place a about:blank in the source and it will work as well in IE, like so: src="about:blank"

    ReplyDelete
    Replies
    1. Thanks for that Nikri, I've updated the blog to include your fix.

      Delete
  6. I used the code in the blog post plus the about:blank suggestion from Nikri and it worked great in IE9. Cheers

    p.s. you should accept donations in bitcoins, its the future.

    ReplyDelete
    Replies
    1. I've just updated the blog to include Nikri's IE fix.

      Bitcoins aye? I took a look at it a while back but had no idea how it worked.

      Delete
  7. Yes, but "about:blank" causes Google to see a 404. Not good!

    ReplyDelete
  8. script blocks are not added to the iframe, so a button onclick doesn't work inside the iframe.

    Example:

    #s c r i p t type="text/javascript">
    function button_click()
    {
    alert('button clicked');
    }
    #/s c r i p t>

    Any idea? Thanx!

    ReplyDelete

Leave your thoughts ...
---
If you are having trouble with copy/pasting in comments, you need to sign in or click 'Preview'. For more information about this Firefox bug, see here.

 
Copyright © Twig's Tech Tips
Theme by BloggerThemes & TopWPThemes Sponsored by iBlogtoBlog