+ 2

Error in the console

i wrote my code in brackets the i paste it after , i finished working but it did't work in the code playground and it worked in my chrome - link : https://www.sololearn.com/Profile/3620140

26th May 2017, 11:24 PM
JohnBerzi
3 Antworten
+ 14
Put all your code in an onload( ) function. onload = function ( ) { // Put all here } // You have no need to call the onload( ) // Remove last line of your code. :3 [ EDIT ] @visph thank you again for your completess, i used the wrong name, naturally i wanted to write "event". Justify me, i wrote it at 3:00 AM 🐍
26th May 2017, 11:27 PM
Maz
Maz - avatar
+ 5
yup, simply remove the onload() call and it works (onload is called automatically once the HTML is loaded) nice game as well :)
27th May 2017, 12:16 AM
Burey
Burey - avatar
+ 5
In sololearn code playground, the JS tab is automatically linked to the Html tab as it was linked in the <head> part... meaning that JS tab code is parsed and ran before <body> tag was loaded/parsed: references to any elements of <body> will so not be available since they are parsed ( available in the DOM -- Document Object Model ). This will explain the error raised ( document.querySelector() is called before any elements exists, so return 'null': when you try to access property of null, it will raised an error, because it have no properties ^^ ) The most quick and simple solution is that suggested by @Maz, but need some adjustement to work: If you simply call your custom all wrapping function ( 'onload' in @Maz example ) at end of JS tab, this will not change anything, as your code is still running before <body> is available... instead of a simple call, you need to assign it to the 'onload' EVENT of the document ( or of the <body> element... but as it will not be acessible at JS tab runtime, you need to set it in the Html code ). So, as explain by @Burey, simply remove your last line call of your onload() function, and replace it with: document.onload = onload; When document is ready to be accessed by JS, the event will fire and your code will be executed, avoiding 'null' results of querySelector(), OR change ( always removing your last onload() call ) your <body> opening tag with: <body onload="onload();"> ... this will produce same behaviour ( and fix your bug-error ;) ). Confusion of @Burey comes from the name choosed in @Maz example ( the 'onload' event will fire automatically and execute function assigned to it, but the 'onload' custom function will be never called if not assigned to an event :P )
27th May 2017, 4:18 AM
visph
visph - avatar