Reputation: 4865
I'm trying to learn the basics of JavaScript I cant figure out why this doesn't work...it's so basic?
<html>
<head>
<meta charset="utf-8" />
<style type="text/css">
ul{
list-style-type:none;
}
div{
width:300px;
height:200px;
background-color:#0066cc;
}
</style>
<script language="text/javascript">
var testing = document.getElementById("addBtn");
testing.addEventListener("click", function(e){ alert("test") } , false);
</script>
</head>
<body>
<ul id="placeholder"></ul>
<a href="#" id="addBtn">Add</a>
</body>
</html>
Upvotes: 1
Views: 5812
Reputation: 33
The other approach you can take is by using the defer
attribute. As the name suggests it defers the load/execution of the script after the whole page has loaded. You just need to add the defer attribute to the opening script tag.
It just works like the window.onload
.
It's something like this
<script defer type="text/javascript">
var testing = document.getElementById("addBtn");
testing.addEventListener("click", function(e){ alert("test") } , false);
</script>
And another way is that you can take this script element and put it right above the closing </body>
tag. I suggest you to always put your script elements just right above your closing body tag and your code would just always work fine.
Upvotes: 1
Reputation: 493
In addition to using window.onload
(which is the key answer to your question), consider using <script>
or <script type="text/javascript">
, as the "language" attribute is deprecated. More info here.
Upvotes: 0
Reputation: 91618
When the code:
var testing = document.getElementById("addBtn");
gets run, the addBtn
element has not yet been parsed. One thing you could do would be to move the <script>
tag down to the bottom of the page.
Another thing you could do is run the code within the onload event. Something like:
<script language="text/javascript">
window.onload = function () {
var testing = document.getElementById("addBtn");
testing.addEventListener("click", function(e){ alert("test") } , false);
};
</script>
Upvotes: 2
Reputation: 60414
The addBtn
is not loaded when you attempt to access it. You should perform that action once the DOM has loaded, either by moving that code to the bottom of the file, or through the onload
event:
window.onload = function() {
var testing = document.getElementById("addBtn");
testing.addEventListener("click", function(e){ alert("test") } , false);
}
Upvotes: 7