Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

focus doesn't work in IE

i have the following function

 function change() 
 {
       var input = document.getElementById('pas');
       var input2 = input.cloneNode(false);
       input2.type = 'password';
       input.parentNode.replaceChild(input2,input);
       input2.focus();
  }

but focus() doesn't work in ie7, so what can i do! i want to have the cursor inside of input!

thanks

update

great solution, thanks, but now it doesn't work in opera:(

like image 818
Simon Avatar asked Apr 08 '10 13:04

Simon


2 Answers

For IE you need to use a settimeout function due to it being lazy, for example:

setTimeout(function() { document.getElementById('myInput').focus(); }, 10);

From http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/

For opera, this may help: how to set focus in required index on textbox for opera

UPDATE:

The following snippet of code handles the case when the element is unavailable and retries after a short period - perfect for slow loading pages and/or elements not available until some time after.

setTimeout(

function( ) {

    var el = document.getElementById( "myInput" ) ;
    ( el != null ) ? el.focus( ) : setTimeout( arguments.callee , 10 ) ;

}

, 10 ) ;
like image 68
zaf Avatar answered Oct 21 '22 05:10

zaf


We hit the same issue. For focusing we are using General function which is applying settimeout solution mentioned in: http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/ with 100 milliseconds.

Still on some screens it's not working properly. Especially when iframes are included. There is another known and similar IE issue:
IE 9 and IE 10 cannot enter text into input text boxes from time to time -> IE 9 and IE 10 cannot enter text into input text boxes from time to time

What I have noticed is when you have focus, without pointer, you can apply workaround by pressing TAB key (focus on next element) and than SHIFT+TAB which will return to our target element with focus and typing pointer. In order to be sure we can type inside input we focus on random element and then on our target input.

$('body').focus();
n.focus();

So we applied the same solution in javascript/JQuery in our general focus function. So there is an if statement

...        
if($.browser.msie) {
    setTimeout(function() { try {
        $('body').focus(); //First focus on random element
        $(n).focus(); //Now focus on target element
    } catch (e) { /*just ignore */ } }, 100); //See http://www.mkyong.com/javascript/focus-is-not-working-in-ie-solution/
} else { //Standard FF, Chrome, Safari solution...
...

To be sure since there is big regression we are still keeping solution with settimeout as a backup. Tested on IE10, IE11, Firefox 45, Chrome 49.0.2623.87

like image 26
Bojan Tadic Avatar answered Oct 21 '22 05:10

Bojan Tadic