Javascript | Why should it be written inside the functions? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
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

28th Jul 2019, 8:22 AM
ewxy
ewxy - avatar
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.
28th Jul 2019, 9:13 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 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.
28th Jul 2019, 8:48 AM
Aaron Eberhardt
Aaron Eberhardt - avatar
28th Jul 2019, 10:10 AM
ewxy
ewxy - avatar
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().
28th Jul 2019, 9:08 AM
ewxy
ewxy - avatar