views:

2522

answers:

5

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: ressponse 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"

A: 
document.getElementsByName("iframe_name")[0].contentWindow.document.body.focus();
Jaime Febres
doesn't seem to work for me
Jimmy
A: 

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

Liam
A: 

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.

Jimmy
+2  A: 

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.

cheeming
+1  A: 

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

danza