user3275701
user3275701

Reputation: 97

Javascript not working from header

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?

Upvotes: 1

Views: 2569

Answers (3)

aksu
aksu

Reputation: 5235

Try to wrap the code in window.onload.

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

Demo!

Upvotes: 2

Tschallacka
Tschallacka

Reputation: 28742

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.

Upvotes: 2

Volkan Ulukut
Volkan Ulukut

Reputation: 4228

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

Upvotes: 0

Related Questions