Window.onload = () => - why won't this work? (JS) | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 3

Window.onload = () => - why won't this work? (JS)

Why doesn't this work? https://code.sololearn.com/WqDee3KleXjP/?ref=app

3rd Jul 2019, 8:28 PM
Ginfio
Ginfio - avatar
5 Answers
+ 4
Variable scopes. The var keyword defines the variable in the function scope, therefore it will only exist inside the function. To make it work, there are two solutions: 1. You declare the variable without any keyword 2. Declare the variable before assigning a value (outside of the function, in the global scope)
3rd Jul 2019, 8:33 PM
Airree
Airree - avatar
+ 3
if u don't necessarily need window onload obj just wanted code to work then. function func(){ var id = document.getElementById('this'); id.style.color="green"; }
4th Jul 2019, 3:39 AM
zexu knub
zexu knub - avatar
+ 2
You can't really use variables before they have an assigned value. You only can use it with events or other asynchronous stuff :/. But this will work: let id; window.onload = () => { id = document.querySelector("#this"); //pretty much the same }; function func() { id.style.color = "green"; } window.onclick = func;
3rd Jul 2019, 8:54 PM
Airree
Airree - avatar
+ 1
Solution 1: "use strict"; let id; //declare id as a global variable window.onload = () => { id = document.getElementById("this"); } const func = () => id.style.color = "green"; Solution 2: //do everything inside window.onload "use strict"; window.onload = () => { let id = document.getElementById("this"); //add on click event listener to id element id.onclick = () => id.style.color = "green"; } Note that solution 2 gets rid of onclick = "func()" inside the div
3rd Jul 2019, 8:46 PM
Haris
Haris - avatar
+ 1
what about this? window...=>{ var x = doc.get...Id('elm'); } How do you use the variables inside the window.onload? outside the window.onload? like ..window.on...{ variables here. } how to use them.here? variable.onclick= func(), variable.addEventListe.... ?
3rd Jul 2019, 8:49 PM
Ginfio
Ginfio - avatar