Capturing events in javascript

152 views Asked by At
<!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....

6

There are 6 answers

0
Alnitak On BEST ANSWER

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);
0
SLaks On

You're calling the function immediately and passing its return value to addEventListener, just like any other function call.
Take out the ().

0
CD.. On

This should work:

document.getElementById('div').addEventListener('click',happen,true);
3
seth.miller On

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);
3
Jeffrey Sweeney On

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).

0
Alfabravo On

The event handler does not need parenthesis

 document.getElementById('div1').addEventListener('click',happen,true);