1

I have problem with simple Javascript code not working from linked file in header but working in browser console for instance. Code is:

document.getElementById("displayname").onfocus = function(){alert("Hello");}

In chrome inspector I can see that script file is linked properly and I can access it in sources tab. I also get this error in loaded script file.

Uncaught TypeError: Cannot set property 'onfocus' of null

What's wrong here?

3 Answers 3

2

This is because your code tries to access something with id "displayname" whilst the DOM isn't finished building and hasn't processed that piece yet where your (presumably input) object is. It processes/build up the dom from the top down.

Place your code in the footer just above the </BODY> tag and it will work beautifully since the DOM will have finished building.

Sign up to request clarification or add additional context in comments.

2 Comments

Thx Michael, that's why $( document ).ready() in JQuery is used, right?
Yes, but new standards / conventions say it's better to place your code just above the </body> tag.
2

Try to wrap the code in window.onload.

window.onload = function() {
   document.getElementById("displayname").onfocus = function(){alert("Hello");}
}

Demo!

Comments

0

The problem is by the time you execute this code displayname object does not exists. when you execute it through console, the object is already there and it runs perfectly. you have two options

  1. put the script after the displayname object
  2. put the script on body onload event

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.