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