+ 4

Problem with Event Listeners

Hey people, As I was practicing my event listeners, I came across the following issue. Check out this code: <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <center> <h1>Code</h1> <button onclick="a()">Click Here!</button> </center> <script> function a(){ document.querySelector("body").style.color = "red"; } document.querySelector("button").addEventListener("click", function (){ document.querySelector("body").style.backgroundColor = "yellow"; }); </script> </body> </html> Now, at first glance, it seems like there is nothing wrong with this code. However, when I place the Javascript part in the coding area that is for Javascript only, it gives me this: Typerror: The document.querySelector(...) is null. I have no idea why it does that. Can someone help me figure out what is the issue with this code? Pretty please?

30th Mar 2019, 11:56 PM
Vasilis Karapas
Vasilis Karapas - avatar
4 Answers
+ 7
start js file with this line: window.onload= function() { //put all your js code here }
31st Mar 2019, 12:35 AM
Ahmad Ali
Ahmad Ali - avatar
+ 7
Thank you, fellas. It never crossed my mind about the different time of execution of JavaScript code, depending on the tag/tab it is pIaced. I just learned something new today :)
31st Mar 2019, 12:52 AM
Vasilis Karapas
Vasilis Karapas - avatar
+ 6
Hi @Vasilis Karapas The code you specified above will execute when the document is already loaded. But if you put that code into the JS tab it will be executed as it would be declared in the <head> section of the HTML and at this time the document is not yet ready (fully loaded) Always put your code into functions and call them when you're sure that the DOM is ready/fully loaded. As an alternative you can put the code that should be executed immediately into a jQuery document.ready function. https://learn.jquery.com/using-jquery-core/document-ready/ The shorthand is: $(function() { ...some code... }); Or use plain JS: https://plainjs.com/javascript/events/running-code-when-the-document-is-ready-15/ Take a look at my code: https://code.sololearn.com/WdKooMrLDwSV/#js
31st Mar 2019, 12:33 AM
Pete Wright
Pete Wright - avatar
+ 1
document.querySelector('body'); can be replaced with document.body, same goes for head
19th Apr 2019, 9:33 PM
RadiatedMonkey
RadiatedMonkey - avatar