Sunday, 1 September 2013

JavaScript focus() function doesn't focus textarea on page load

JavaScript focus() function doesn't focus textarea on page load

I have the following code.
<!DOCTYPE html>
<html>
<head>
<title>Focus issue</title>
<script type='text/javascript'>//<![CDATA[
window.onload=function(){
var text = document.getElementById('text')
window.onload = function() {
text.focus()
}
window.onhashchange = function() {
text.focus()
}
}//]]>
</script>
</head>
<body>
<textarea id="text"></textarea>
<p><a href="#focus">Click to focus</a></p>
</body>
</html>
Here is a JSFiddle demo of the above code: http://jsfiddle.net/DvU63/
Why doesn't the focus go on the textarea box when the page loads? On
clicking the link, the focus does go on the textarea box, but I also want
the focus to go to the textarea box on page load. Why doesn't it happen?
Note: I am aware of the HTML5 autofocus attribute for textarea. But this
question is about why the above JavaScript code does not do what I intend
to do.

No comments:

Post a Comment