Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"

like image 214
Jimmy Avatar asked Dec 15 '08 17:12

Jimmy


People also ask

How do I focus an iframe element?

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

How to set focus on iframe using JavaScript?

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

What is #document in iframe?

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.


1 Answers

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.

like image 112
cheeming Avatar answered Sep 21 '22 00:09

cheeming