+ 2

why addEventListener is not working?

I used an event listener method in my code which is working fine in my another code editor but it's not working here and throwing an error. https://code.sololearn.com/Wd4NYQ8MbXQb/?ref=app

23rd May 2021, 4:07 PM
Junaid Shaikh[Inactive]
Junaid Shaikh[Inactive] - avatar
3 Answers
+ 5
This is because javascript is loaded before html. One way to avoid this is as follows use the onload event: onload = ()=>{ Your javascript } Specifically in your case, you do not need to declare the btn variable, since it has already been declared as a global variable of the html document (id = "btn"), you just need to wait for the html document to load to access it, for this you can use the onload event again: onload=()=>btn.addEventListener('click', function (){ ... }
23rd May 2021, 4:27 PM
Solo - avatar
+ 1
where is the code?
23rd May 2021, 4:08 PM
Matias - avatar
+ 1
Great code. 👏👏👏👏👏👍 Try the second option, it is better for the given code, or even better this option: onload=()=>btn.onclick=(){ ☺️ } P. S: "The addEventListener method is used to add a event to an existing one, and you only have one event."
23rd May 2021, 5:07 PM
Solo - avatar