Reputation: 131
i was wondering why I can't add an Event Listener inside my DOMContentLoaded function, my problem is that he fires the click before it loads and then doesnt do anything after:
HTML
<body>
This is a test.<br>
</body>
JS //DOMContentLoaded...
var btn=document.createElement("BUTTON");
var t=document.createTextNode("CLICK ME");
btn.appendChild(t);
document.body.appendChild(btn);
btn.addEventListener('click',alert('HELLO!'),false);
I made a fiddle of this: http://jsfiddle.net/hH5Lh/
I have to use DOMContentLoaded because on my code I have XMLHTTP requests that can only be triggered after my html has been loaded...
How can I fix this?
Upvotes: 1
Views: 1296
Reputation: 227280
This is because you need to assign a function as the event callback. alert('HELLO!')
will call the alert
function and pass its return value (undefined
) as the event callback.
You want to do this:
btn.addEventListener('click', function(){
alert('HELLO!');
}, false);
Upvotes: 3