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 Respostas
+ 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().