Monday, May 20, 2024
72
rated 0 times [  79] [ 7]  / answers: 1 / hits: 64952  / 12 Years ago, thu, may 31, 2012, 12:00:00

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.


More From » addeventlistener

 Answers
3

First of all, you should access the body element through document.body. However, onload is defined on window, so you actually need:



window.onload = init();


However, that would execute the init() method and store the return value in window.onload. Obviously, that's not what you want: you want the init function to act as onload handler. Therefore, you should have written:



window.onload = init;


Although I'd recommend using addEventListener for that as well:



window.addEventListener(load, init);

[#85235] Wednesday, May 30, 2012, 12 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
susanajamiep

Total Points: 466
Total Questions: 113
Total Answers: 108

Location: Liberia
Member since Fri, Oct 22, 2021
3 Years ago
susanajamiep questions
Sun, Jun 12, 22, 00:00, 2 Years ago
Mon, Mar 7, 22, 00:00, 2 Years ago
Wed, Jun 10, 20, 00:00, 4 Years ago
Fri, Jan 24, 20, 00:00, 4 Years ago
;