Capturing events in javascript
-
19-04-2021 - |
Pergunta
<!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....
Solução
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);
Outras dicas
You're calling the function immediately and passing its return value to addEventListener
, just like any other function call.
Take out the ()
.
This should work:
document.getElementById('div').addEventListener('click',happen,true);
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);
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).
The event handler does not need parenthesis
document.getElementById('div1').addEventListener('click',happen,true);