views:

602

answers:

3

There is a tree menu in my application and on click of the menu items, it loads a url in a iFrame. I like to set the focus in an element of the page loaded in the iFrame.

I'm using this code, and it works perfectly in all the browsers except IE:

var myIFrame = $("#iframeName");
myIFrame.focus();
myIFrame.contents().find('#inputName').focus();

I have tried all different options like using setTimeout, but no chance.

After the page loads, when I hit the tab key, it goes to the second input, which means it's been on the first input, but it doesn't show the cursor!

I am using ExtJS and the ManagedIFrame plugin.

Any help is appreciated.

+3  A: 

Is the iFrame visible onload, or shown later? The elements are created in different order which is the basis of the setTimeout approach. Did you try a high value wait time on a set timeout?

Try something like at least a half second to test...IE tends to do things in a different order, so a high timeout may be needed to get it not to fire until render/paint finishes:

$(function(){
  setTimeout(function() {
    var myIFrame = $("#iframeName");
    myIFrame.focus();
    myIFrame.contents().find('#inputName').focus();
    }, 500);
});
Nick Craver
Well, I even tried it with 1000 before. One more thing which may help, it shows the cursor for a moment, and the cursor goes away immediately! As I said in the question, after I hit the tab, it goes to the next input box. It just doesn't displays the cursor.Also, the iframe is visible onload, but sets the src later, each time the user clicks on a menu item.
Amin Emami
Are you focusing each time the iframe src changes?
Nick Craver
Yes, I am. It set the focus right after documentloaded event each time.
Amin Emami
+1  A: 

You need to call the focus() method of the iframe's window object, not the iframe element. I'm no expert in either jQuery or ExtJS, so my example below uses neither.

function focusIframe(iframeEl) {
    if (iframeEl.contentWindow) {
        iframeEl.contentWindow.focus();
    } else if (iframeEl.contentDocument && iframeEl.contentDocument.documentElement) {
        // For old versions of Safari
        iframeEl.contentDocument.documentElement.focus();
    }
}
Tim Down
I tried it and it didn't work.
Amin Emami
+1  A: 

Difficult to troubleshoot without a working example, but you might try hiding and showing the input as well, to force IE to redraw the element.

Something like:

var myIFrame = $("#iframeName");
myIFrame.focus();
myIFrame.contents().find('#inputName').hide();
var x = 1;
myIFrame.contents().find('#inputName').show().focus();

This might jolt IE into displaying the cursor.

honeybuzzer