+ 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
3 Respuestas
+ 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 (){ ... }
+ 1
where is the code?
+ 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."