javascript - Declaring an image variable in global scope is not getting assigned but inside a function does -
this question has answer here:
i trying create functionality in plain javascript in order make images appear , disappear under condition. assigned images id's , created function : (the overall functionality removed make things simpler since not conflict current problem whatsoever) when call function image disappears screen expected.
function imageoff() { var img = document.getelementbyid("theimage"); img.style.opacity = "0"; } however, if declare outside function global image not dissapear , variable undefined when try console.log(img):
var img = document.getelementbyid("theimage"); img.style.opacity = "0"; the reason need assign opacity value of image users goes website once instead of executing every single time function called!
the problem that, assigning variable img before loading dom.
var img = document.getelementbyid("theimage"); if place/wrap of code onload function of window, problem should resolve since onload makes sure dom load.
window.onload = function(){ var img = document.getelementbyid("theimage"); ... functions ().. } it working when place in function because, time executing function dom got loaded.
Comments
Post a Comment