skip to content

jQuery Edge: Better Support for other Windows and Documents

1 min read

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()](” title=“Docs for contents method), 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

// Get height of iframe document

// 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.