Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Setting Focus to an iFrame in IE

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.

like image 884
Amin Emami Avatar asked Jan 11 '10 23:01

Amin Emami


3 Answers

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();
    }
}
like image 111
Tim Down Avatar answered Oct 23 '22 04:10

Tim Down


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);
});
like image 3
Nick Craver Avatar answered Oct 23 '22 04:10

Nick Craver


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.

like image 1
honeybuzzer Avatar answered Oct 23 '22 04:10

honeybuzzer