If you, like me, work with legacy enterprise web applications, you may need to run the web applications in a legacy document mode. This allows support for non-compliant markup that works with old versions of Internet Explorer. When you then add new content that requires modern web browser functionality, you may find yourself placing said content inside an iFrame, specifying a modern document type or X-UA-Compatible mode. I recently needed to bind to an event inside such an iFrame using jQuery. I was stuck on this problem for quite a while, able to grab every detail about the object using jQuery, but seemingly unable to use jQuery to bind to an event in a child iFrame.
If you want to bind to an event in a child iFrame, you need to access the jQuery function that lives inside the iFrame!
document.getElementById('my_iFrame').contentWindow.$("#itemInIFrameIWantToSelect").on( "click", function() { alert( "Element inside an iFrame was clicked!" ); }); |
In the above example, we get an iFrame by Id, then grab the content window for the iFrame. From there, we access the instance of the jQuery function, $()
, that lives inside of this embedded content window and bind to the click
event on the element with an id of itemInIFrameIWantToSelect
. This is a different instance of the jQuery function from the jQuery function that lives in the main content page. The jQuery function in the main content page can select DOM elements inside the iFrame, but only the inner jQuery function is able to bind to events on these elements.