Reputation: 574
Does this code work for anyone else. For the longest time adding an event listener hasn't worked.
<head>
<title>Page Title</title>
<script>
window.onload = init();
function init() {
svg = document.getElementsByTagName('svg');
svg[0].addEventListener('click', mouseClick, false);
}
function mouseClick() {
alert('mouseClicked');
}
</script>
</head>
<body>
<svg><rect x="100" y="100" width="200" height="75"/></svg>
</body>
For every project I've worked on, I've had to use an alternative method. Am I doing something wrong with "addEventListener"? Or what?
Upvotes: 0
Views: 132
Reputation: 11922
Your problem is:
window.onload = init();
By including the brackets, you're calling the function at that point, so what you're doing is assigning the result of a call to init to window.onload. You need:
window.onload = init;
which will assign the function init to window.onload.
Upvotes: 1
Reputation: 96790
init()
calls the function and unless it returns a function, this will not work. What you need to do is pass the function, not the return value thereof:
window.onload = init;
Upvotes: 1