Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 422
Lone Learner Avatar asked Aug 25 '26 23:08

Lone Learner


1 Answers

You're doing the .focus() statement from inside an onload handler that is itself defined inside an onload handler. This inner onload will not be called because by the time you define it the onload event will have occurred. Try this:

window.onload=function(){
  var text = document.getElementById('text')
  text.focus()

  window.onhashchange = function() {
    text.focus()
  }
}

Your demo, updated: http://jsfiddle.net/DvU63/2/

like image 58
nnnnnn Avatar answered Aug 28 '26 11:08

nnnnnn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!