Why my addEventListener don't work? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

Why my addEventListener don't work?

I want to do a button which will create a new div element. https://code.sololearn.com/WMwPhmWVXVM7/?ref=app

19th Apr 2021, 11:12 AM
Alek Levun
Alek Levun - avatar
4 Answers
+ 6
Your addEventListener is fine. The problem is that your btn isn't what you think it is because you need to wait for the document to load before you can select elements. /* Updated: used document instead of window because it's quicker */ document.addEventListener("DOMContentLoaded", () =>{ // now the document has loaded // so, you can put your code here })
19th Apr 2021, 11:19 AM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 2
Alek Levun You won't have this problem if you put all your JavaScript in a script tag in your HTML but then all your JavaScript would be in your HTML file and that in my opinion is a much bigger problem.
19th Apr 2021, 3:37 PM
CamelBeatsSnake
CamelBeatsSnake - avatar
+ 1
Thanks, i know about this problem, but i thought that i'll not have this problem in this aplikation. I'm styding on the laptop in vscode.
19th Apr 2021, 3:25 PM
Alek Levun
Alek Levun - avatar
+ 1
Based on some experimenting, I've discovered differences in load order in the way the SL App assembles the various bits on Android vs iOS vs browser. https://code.sololearn.com/Wa16A20a6a23/?ref=app Due to the nature of asynchronous file loading over HTTP and bizarre loading discrepancies on SL, it's a good idea to isolate DOM access to code that's guaranteed to execute after the DOM has loaded... as presented by CamelBeatsSnake. On that note... his original answer should be marked as the correct answer. 😉👌
19th Apr 2021, 5:55 PM
David Carroll
David Carroll - avatar