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').onfoc
Solution 1:
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.
Solution 2:
Try to wrap the code in window.onload
.
window.onload = function() {
document.getElementById("displayname").onfocus = function(){alert("Hello");}
}
Solution 3:
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
- put the script after the displayname object
- put the script on body onload event
Solution 4:
this is simpler way of doing the same
try this
Enter your name: <inputid="displayname"type="text" onfocus="myFunction(this)">
refrence http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onfocus
Post a Comment for "Javascript Not Working From Header"