Reputation: 97
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
Reputation: 5235
Try to wrap the code in window.onload
.
window.onload = function() {
document.getElementById("displayname").onfocus = function(){alert("Hello");}
}
Upvotes: 2
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
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
Upvotes: 0