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"
If you're trying to set focus to an element in an iframe that has already been loaded, you need to set focus to the iframe first, then to the element. myField. focus();
function setFocusThickboxIframe() { var iframe = $("#TB_iframeContent")[0]; iframe. contentWindow. focus(); } $(document). ready(function(){ $("#id_cmd_open").
Definition and Usage. The contentDocument property returns the Document object generated by a frame or iframe element. This property can be used in the host window to access the Document object that belongs to a frame or iframe element.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With