+ 8

Element not defined?

Hi, I have just come across this problem were i can use the number variable inside the function but i cant use the image variable as element is not defined? what does that mean please as i thought my variables were global? thanks var number = 50; var image = document.getElementById("ball"); window.onload = function fun(){ image.style.left = number+'px'; }

20th Jul 2018, 4:30 PM
D_Stark
D_Stark - avatar
7 odpowiedzi
+ 8
heres what you should do: var number = 50; var image ; window.onload = function fun(){ image=document.getElementById("ball"); image.style.left = number+'px'; } declare your image variable globally.. then store your element in it after the DOM has fully loaded
20th Jul 2018, 5:32 PM
᠌᠌Code X
᠌᠌Code X - avatar
+ 5
You are doing var image = document.getElementById("ball") before the function window.onload... The most likely is that maybe the DOM was not finished been created when you tried to get the element with Id "ball". You might want to move it inside the window.onload function
20th Jul 2018, 5:30 PM
cyk
cyk - avatar
+ 5
Looks like image was referenced before the DOM is ready? maybe place the image = document.getElementById("ball") within function fun()?
20th Jul 2018, 5:31 PM
Ipang
+ 5
᠌᠌brains Thanks i understand that it works inside a the parent function just wondering why this way didnt work outside of it, i think ill learn more about the DOM as im still unsure how js is interpreted its actually very diffrent compared to java becuase theres no classes 😅
20th Jul 2018, 6:12 PM
D_Stark
D_Stark - avatar
+ 1
Link the whole code, looks fine so far
20th Jul 2018, 5:05 PM
TurtleShell
TurtleShell - avatar
0
D_Stark there are classes in java script , wish you are going to use these soon😂
22nd Jul 2018, 10:14 AM
Chandan Kumar Mandal
Chandan Kumar Mandal - avatar