Home > Article > Web Front-end > Why Doesn\'t `focus()` Work in Internet Explorer and Opera?
Focusing Input Fields in Internet Explorer and Opera
When using the focus() method in JavaScript, some issues may arise in certain browsers. This question highlights a problem where focus() does not work in Internet Explorer 7, leaving the cursor outside the desired input field.
Solution for Internet Explorer:
In Internet Explorer, focus() requires some additional attention due to its lazy nature. To fix this issue, utilize the setTimeout() function. For example:
setTimeout(function() { document.getElementById('myInput').focus(); }, 10);
Solution for Opera:
For Opera, consider exploring solutions related to setting focus in required index on textbox.
Improved Handling for Delayed Element Availability:
In some cases, the element may not be available immediately, resulting in an unfocused input field. To address this, the following improved code retries the focus after a short interval:
setTimeout( function( ) { var el = document.getElementById( "myInput" ) ; ( el != null ) ? el.focus( ) : setTimeout( arguments.callee , 10 ) ; } , 10 ) ;
The above is the detailed content of Why Doesn\'t `focus()` Work in Internet Explorer and Opera?. For more information, please follow other related articles on the PHP Chinese website!