[javascript] Setting focus to iframe contents

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"

This question is related to javascript dom iframe setfocus

The answer is


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.


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


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


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?


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


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.


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(); 

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


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


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

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


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.


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


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(); 

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

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


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?


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

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.


Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to dom

How do you set the document title in React? How to find if element with specific id exists or not Cannot read property 'style' of undefined -- Uncaught Type Error adding text to an existing text element in javascript via DOM Violation Long running JavaScript task took xx ms How to get `DOM Element` in Angular 2? Angular2, what is the correct way to disable an anchor element? React.js: How to append a component on click? Detect click outside React component DOM element to corresponding vue.js component

Examples related to iframe

Getting all files in directory with ajax YouTube Autoplay not working Inserting the iframe into react component How to disable auto-play for local video in iframe iframe refuses to display iFrame onload JavaScript event YouTube iframe embed - full screen Change New Google Recaptcha (v2) Width load iframe in bootstrap modal Responsive iframe using Bootstrap

Examples related to setfocus

Set element focus in angular way Correct way to focus an element in Selenium WebDriver using Java How to Set Focus on JTextField? how to put focus on TextBox when the form load? Set focus to field in dynamically loaded DIV Setting focus to iframe contents