Had a gnarly problem this afternoon, while trying to set focus to a control in an IFRAME.
Using JQuery, I had created the IFRAME with the JQuery plugin
ThickBox. ThickBox provides functionality that can simulate a modal dialog using an IFRAME, loading a page from a URL into the IFRAME (
check out the demo here - scroll down to "Inline Content"). The page loaded inside the IFRAME contained code to set the focus which was actually being called, but
after the page loaded something else was stealing the focus.
I began to look at the javascript code in the parent that created the IFRAME.
I discovered to set the focus to a control in an IFRAME that has already been loaded, you need to set the focus to the IFRAME first (thanks Alex King). I also benefited from "How to access IFRAME in JQuery" over at ProCoding (thanks Taras Ilnytskyy).
Here's the code to set focus to a control in an IFRAME using JQuery (called from the parent window, after the IFRAME has been loaded and shown):
//get the IFRAME element - note no hashes in the name, we're using browser functionality
var iframeRef = document.getElementById("IFRAMEID");
//focus the IFRAME element
$(iframeRef).focus();
//use JQuery to find the control in the IFRAME and set focus
$(iframeRef).contents().find("#CONTROLID").focus();
I hope this helps someone!
UPDATE: Fixed formatting.
Tags: jquery, javascript, web, iframe
posted @ Thursday, May 28, 2009 2:58 PM