0
Javascript | Why should it be written inside the functions?
Why canât it work if I put âvar slider = document.getElementById("slider");â before functions? https://code.sololearn.com/WRhnWVcVaUCU/?ref=app
4 Answers
+ 1
ewxy yep I know. It doesn't work if used before next() and prev() because the code runs to early and the element with id "slider" doesn't exist. Only if it is run later (e.g. inside next()) it works because then the whole html is loaded and the element you're looking for exists.
+ 1
It doesn't work because the JS tab will be converted to a script tag inside the head of the html. The head is loaded before the body so the JS is executed before all elements are loaded. Therefore document.getElementsById returns null because it can't find that element yet. To solve this, you could e.g. define var slider globally and the define it inside
window.onload = () => { /* code * }
so the code will only run when all elements are loaded.
+ 1
ty :) Aaron Eberhardt
0
Thanks a lot. I mean why I have to define âvar slider = document.getElementById("slider");â for two times? It doesnât work if I define it before I define next() and prev().