Lone Learner
Lone Learner

Reputation: 20698

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.

Upvotes: 3

Views: 2975

Answers (2)

Milad Hosseinpanahi
Milad Hosseinpanahi

Reputation: 1505

do this

<script type='text/javascript'> 
    window.onload=function(){
    var text = document.getElementById('text')

    text.focus();

    window.onhashchange = function() {
        text.focus();
    }
  }
</script>

fiddle

Upvotes: 1

nnnnnn
nnnnnn

Reputation: 150070

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/

Upvotes: 5

Related Questions