Setting focus to iframe contents

JavascriptDomIframeSetfocus

Javascript Problem Overview


I have a page with a document.onkeydown event handler, and I'm loading it inside an iframe in another page. I have to click inside the iframe to get the content page to start "listening".

Is there some way I can use JavaScript in the outer page to set the focus to the inner page so I don't have to click inside the iframe?

EDIT: response to comment:

The context is the main window is a light-box-like system, except instead of pictures, it shows iframes, and each iframe is an interactive page with keydown/mousemove handlers. these handlers don't fire until I click in the iframe after showing the light-box-thing.

I'm not actually looking to "setFocus" in the traditional sense as much as "enable event handlers on the iframe contentDocument"

Javascript Solutions


Solution 1 - Javascript

I had a similar problem with the jQuery Thickbox (a lightbox-style dialog widget). The way I fixed my problem is as follows:

function setFocusThickboxIframe() {
    var iframe = $("#TB_iframeContent")[0];
    iframe.contentWindow.focus();
}

$(document).ready(function(){
   $("#id_cmd_open").click(function(){
      /*
         run thickbox code here to open lightbox,
         like tb_show("google this!", "http://www.google.com");
       */
      setTimeout(setFocusThickboxIframe, 100);
      return false;
   });
});

The code doesn't seem to work without the setTimeout(). Based on my testing, it works in Firefox3.5, Safari4, Chrome4, IE7 and IE6.

Solution 2 - Javascript

Using the contentWindow.focus() method, the timeout is probably necessary to wait for the iframe to be completely loaded.

For me, also using attribute onload="this.contentWindow.focus()" works, with firefox, into the iframe tag

Solution 3 - Javascript

document.getElementsByName("iframe_name")[0].contentWindow.document.body.focus();

Solution 4 - Javascript

Try listening for events in the parent document and passing the event to a handler in the iframe document.

Solution 5 - Javascript

i had a similar problem where i was trying to focus on a txt area in an iframe loaded from another page. in most cases it work. There was an issue where it would fire in FF when the iFrame was loaded but before it was visible. so the focus never seemed to be set correctly.

i worked around this with a simular solution to cheeming's answer above

	var iframeID = document.getElementById("modalIFrame"); 
//focus the IFRAME element 
$(iframeID).focus(); 
//use JQuery to find the control in the IFRAME and set focus 
$(iframeID).contents().find("#emailTxt").focus(); 

Solution 6 - Javascript

I discovered that FF triggers the focus event for iframe.contentWindow but not for iframe.contentWindow.document. Chrome for example can handle both cases. so, I just needed to bind my event handlers to iframe.contentWindow in order to get things working. Maybe this helps somebody ...

Solution 7 - Javascript

Here is code to create an iframe using jQuery, append it to the document, poll it until it is loaded, then focus it. This is better than setting an arbitrary timeout which may or may not work depending on how long the iframe takes to load.

var jqueryIframe = $('<iframe>', {
	src: "http://example.com"
}),
focusWhenReady = function(){
	var iframe = jqueryIframe[0],
	doc = iframe.contentDocument || iframe.contentWindow.document;
	if (doc.readyState == "complete") {
		iframe.contentWindow.focus();
	} else {
		setTimeout(focusWhenReady, 100)
	}
}
$(document).append(jqueryIframe);
setTimeout(focusWhenReady, 10);

The code for detecting when the iframe is loaded was adapted from Biranchi's answer to How to check if iframe is loaded or it has a content?

Solution 8 - Javascript

This is something that worked for me, although it smells a bit wrong:

var iframe = ...
var doc = iframe.contentDocument;

var i = doc.createElement('input');
i.style.display = 'none'; 
doc.body.appendChild(i);
i.focus();
doc.body.removeChild(i);

hmmm. it also scrolls to the bottom of the content. Guess I should be inserting the dummy textbox at the top.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionJimmyView Question on Stackoverflow
Solution 1 - JavascriptcheemingView Answer on Stackoverflow
Solution 2 - JavascriptdanzaView Answer on Stackoverflow
Solution 3 - JavascriptJaime FebresView Answer on Stackoverflow
Solution 4 - JavascriptLiamView Answer on Stackoverflow
Solution 5 - Javascriptnate_weldonView Answer on Stackoverflow
Solution 6 - JavascriptmileView Answer on Stackoverflow
Solution 7 - JavascriptStephen OstermillerView Answer on Stackoverflow
Solution 8 - JavascriptJimmyView Answer on Stackoverflow