The focus() method is used to give focus to a textbox, or other html components. Here is a simple example to make a textbox focus automatically after page load.

<html>
 
<head>
<title>focus is not working in IE</title>
</head>
<body>
 
<form >
    <input id="myInput" type="text" value='testing'><br>
</form>
</body>
 
 <script type="text/javascript">
	document.getElementById('myInput').focus();
</script>
 
</html>

The above code is working fine in Firefox (FF), but not in Internet Explorer (IE). Actually the IE is supporting the focus() method, we just need to use other way to write the focus method.

Base on my personal observation, this is because IE run the focus() method before the textbox render properly. However the Javascript is put after the textbox, the focus() method suppose to execute after textbox fully render itself, may be IE treat it as different ways? Ya, IE always have “IE-ONLY” implementation…

Here is an unofficial solution, we have to use the setTimeout() fucntion to delay the focus() execute time.

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

After delay the execute time, the focus() is working fine in IE , or even FF.

<html>
 
<head>
<title>focus is working in IE</title>
</head>
<body>
 
<form >
    <input id="myInput" type="text" value='testing'><br>
</form>
</body>
 
 <script type="text/javascript">
	setTimeout(function() { document.getElementById('myInput').focus(); }, 1000);
</script>
 
</html>

Reference

setTimeout() – http://www.w3schools.com/htmldom/met_win_settimeout.asp

Tags :
Founder of Mkyong.com and HostingCompass.com, love Java and open source stuff. Follow him on Twitter, or befriend him on Facebook or Google Plus. If you like my tutorials, consider making a donation to this charity, thanks.

Related Posts

Popular Posts