AddEventListener not working with onClick
10,976
There are at least three things wrong here:
- The event name for use with
addEventLisener()
is"click"
, not"onclick"
. - You should use the window
load
event OR theDOMContentLoaded
event, but not both. - Your click handler function isn't actually doing anything. Did you mean to call a function like
winPrize();
?
So, cleaning all of those issues, you would have this:
document.addEventListener('DOMContentLoaded', function() {
document.getElementById("wheelContainer").addEventListener("click", function() { winPrize();
}, false);
});
You don't need the init()
function or the window load event handler at all since you can just install the event handler when the DOMContendLoaded
event fires.
Author by
Lilu Patel
Updated on June 13, 2022Comments
-
Lilu Patel almost 2 years
I am trying to use windows.addEventListener to execute my function on clicking a div. However nothing is happening.
This is my code:
Javascript:
window.addEventListener('load', init); function init(){ document.addEventListener('DOMContentLoaded', function() { document.getElementById("wheelContainer").addEventListener("onclick", function() { winPrize; }, false); }); }
Can someone please tell me what am I doing wrong.
Thankyou.
-
crush over 10 years"onclick" would be used for
attachEvent
for legacy IE support. I want to upvote this answer, but daily limit reached :( -
Lilu Patel over 10 yearsSo If I remove the windows load event and just have the Document add event listener event it should work?: document.addEventListener('DOMContentLoaded', function() { document.getElementById("clickToPlay").addEventListener("click", function() { winPrize; }, false); });
-
jfriend00 over 10 years@NiraliPatel - yes, that should work as I've added to the end of my answer.
-
Lilu Patel over 10 years@jfriend00 - I have edited my code as above and its still not working. I have tried it in IE11 and Firefox26.0. When I added the function directly to the windows event (did not bind it to any element) it worked correctly. I am not sure how to fix this :|
-
jfriend00 over 10 years@NiraliPatel - the other thing I noticed is that your click event handler isn't actually doing anything. You just have
winPrize;
in the event handler, but that doesn't do anything. Did you mean to make it a function call likewinPrize();
? -
Lilu Patel over 10 years@jfriend00 - Yes Thankyou! I did mean to make it a function call!! It works now.