Ok, so I tried to make this page with an addEventListener function, to address the clicking of a button; It didn’t work. I narrowed it down by deleting everything but the basic elements needed for the listener, and am left with the following:
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
function init(){
document.getElementById("test").addEventListener("mousedown", function(){
alert("Test successful");
});
}
body.onload = init();
</script>
</head>
<body>
<button id="test">Click</button>
</body>
</html>
which didn’t work either, so I know the issue is in my syntax of the above. Mind you, when I took away body.onload = init(); and instead put onload="init()" into the body tag, it did work :O Problem is, I don’t want to have it inline. Any suggestions?
Note: Do bear in mind that this question is not about how there is a bug in JS, even if the title may suggest so, it is about how I can’t get it to work since I’ve probably got the syntax wrong. Please feel free to rename it if you wish.
First of all, you should access the body element through
document.body. However,onloadis defined onwindow, so you actually need:However, that would execute the
init()method and store the return value inwindow.onload. Obviously, that’s not what you want: you want theinitfunction to act asonloadhandler. Therefore, you should have written:Although I’d recommend using
addEventListenerfor that as well: