Could somebody please explain why this button does not work? The error in my console indicates that var button = document.getElementById('next');
is returning null
.
HTML:
<!DOCTYPE html>
<html lang="en">
<head>
<script>
...
</script>
</head>
<body>
<button id="next">Say hi</button>
</body>
</html>
Javascript:
var button = document.getElementById('next');
function sayHi(){
alert('Hi there');
}
button.addEventListener('click',sayHi,false);
Thanks for your help
Run the JS after the HTML has loaded. When you call the JS in the head, the button doesn't exist yet, it's rendered after the JS is called.
This will work:
<!DOCTYPE html>
<html lang="en">
<head>
</head>
<body>
<button id="next">Say hi</button>
<script type="text/javascript">
...
</script>
</body>
</html>
At the time the script runs you have no element with the id next
.
<script>
element so it appears after the element with that id or
e.g.
function sayHi(){
alert('Hi there');
}
function setUpButton() {
var button = document.getElementById('next');
button.addEventListener('click',sayHi,false);
}
addEventListener('load', setUpButton);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With