Setting Focus to an iFrame in IE

10,982

Solution 1

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

Solution 2

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

Solution 3

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.

Share:
10,982
Amin Emami
Author by

Amin Emami

Software Engineer

Updated on July 11, 2022

Comments

  • Amin Emami
    Amin Emami almost 2 years

    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.