0

Javascript not working in code playground

As a learner, I've tried some codes in Code playground, so I started to code in Javascript tab that would apply a click event listener to a div, using addEventListener (), but the code resulted in error. After googling it, I find out that some of these errors are due that some HTML elements are not fully loaded and would be advisable to put javascript code at the bottom of <body> tag. I did it, and the same code worked. So, should I always put my JS code at the end of body and not using the Javascript tab?

21st May 2017, 5:30 PM
Tiago Soares
Tiago Soares - avatar
4 ответов
+ 5
use window.onload = function() {eventListeners here} in your JS file and just leave the HTML. The window.onload thing will invoke the function when the whole HTML file is done loading.
21st May 2017, 5:44 PM
The Coding Sloth
The Coding Sloth - avatar
+ 3
try: window.onload = function() { document.getElementById ("myElement").addEventListener("click", function() { alert("click"); });
22nd May 2017, 5:06 AM
The Coding Sloth
The Coding Sloth - avatar
0
I tried: window.onload=document.getElementById (myElement).addEventListener ("click", function {}); But it happened the same problem
21st May 2017, 7:41 PM
Tiago Soares
Tiago Soares - avatar