jQuery Edge: Better Support for other Windows and Documents

Thursday, May 14, 2009

jQuery in the past hasn’t always played well with other windows and documents than the one it was loaded in. However, jQuery is moving in the right direction to help ease the pain of cross window/frame development. There have been several commits recently that make previously window/document dependent methods, well… less dependent. So far .bind(), .css(), .width(), and .height() have all been updated to work with other windows and documents.

So, how might you use this new found jQuery power? First, if you didn’t already know jQuery has a method, called .contents(), that when used on an iframe element returns the document of the iframe.

// Get a reference to the iframe document
var iframeDoc = $('iframe').contents().get(0);

Now we can bind an event to it, get the dimensions, get styles of various elements, etc.

// Get width of iframe document
$(iframeDoc).width();

// Get height of iframe document
$(iframeDoc).height();

// Bind event to iframe document
$(iframeDoc).bind('click', function( event ) {
    // do something
});

// Get the style of an element in the iframe
$('div', iframeDoc).css('backgroundColor');

Simple as that.

Posted in jQuery, jQuery Edge with 5 comments

Comments

Will this work now?

$(iframeDoc).bind('load', function( event ) {
    // do something
});

Thanks!

By Matt W. on Thursday, May 14, 2009 at 10:30 PM

@Matt, You may run into some timing issues depending on when you bind the load event but it will bind the event to the correct window/document. You would probably get better results actually binding to the iframe window though. You could do that like this:

var iframeWin = $('iframe')[0].contentWindow;
iframeWin.name = 'iframe';
$(iframeWin).bind('load', function(event) {
    alert( this.name + ' is now loaded' );
});

By Brandon Aaron on Friday, May 15, 2009 at 01:00 AM

Can we get these?

$("iframe").width();
$("iframe a").click();

By Jörn Zaefferer on Friday, May 15, 2009 at 12:16 PM

@Jörn, I don’t believe there is a good way to make the proposed syntax work well. However, I did go ahead and create a new plugin to make it easier to use iframe documents and windows.

It allows syntax like this:

$('iframe').win().bind('load', fn);
$('iframe').doc().find('a').click(fn);

By Brandon Aaron on Friday, May 15, 2009 at 04:37 PM

Thats cool. Should come in handy next I’m working with iframes.

By Jörn Zaefferer on Saturday, May 16, 2009 at 11:57 AM

New Comment