Reputation: 6291
<!doctype html>
<html>
<body>
<div id = 'div' style = 'width:100px;height:100px;background:#000000;'></div>
<script type = 'text/javascript'>
document.getElementById('div').addEventListener('click',happen(),true);
function happen()
{
alert(1)
}
</script>
</body>
</html>
In the above code why the event is triggered when the page loads and not triggered when i click on the div...Also which is the correct event name click or onclick....
Upvotes: 0
Views: 165
Reputation: 7589
The event handler does not need parenthesis
document.getElementById('div1').addEventListener('click',happen,true);
Upvotes: 0
Reputation: 6124
As the other answerers have said, taking out the () will fix the problem.
An alternative, and a good practice for OO Javascript, is to wrap the function inside a function(){ }
, like so:
document.getElementById('div').addEventListener('click',function(){happen()},true);
That will retain scope if the callback needs to execute within an object (in this case it does not).
Upvotes: 0
Reputation: 1988
The problem is with this line:
document.getElementById('div').addEventListener('click',happen(),true);
You should should only be passing the name of the function happen
but since you added the parentheses, you are passing the result.
Try this instead:
document.getElementById('div').addEventListener('click',happen,true);
Upvotes: 2
Reputation: 339917
It's because you've immediately called the function, and passed its null result to addEventListener()
.
It should be:
document.getElementById('div').addEventListener('click',happen,true);
If you want to pass arguments to happen
, you'd have to write this:
document.getElementById('div').addEventListener('click', function() {
happen(args_here, ...);
}, true);
Upvotes: 3
Reputation: 74166
This should work:
document.getElementById('div').addEventListener('click',happen,true);
Upvotes: 2
Reputation: 887777
You're calling the function immediately and passing its return value to addEventListener
, just like any other function call.
Take out the ()
.
Upvotes: 3