2

i am trying to create a functionality in plain javascript in order to make some images appear and disappear under a certain condition. So assigned to the images their id's and created this function : (the overall functionality was removed just to make things simpler since they do not conflict with the current problem whatsoever) When i call the function the image successfully disappears from the screen as expected.

function imageOff()
{
var img = document.getElementById("theimage");
img.style.opacity = "0";
}

However, if i declare this outside that function as a global the image does not dissapear and i also get that the variable is undefined when i try to console.log(img):

var img = document.getElementById("theimage");
img.style.opacity = "0";

The reason i need this is to assign the opacity value of that image as soon as the users goes to the website just once instead of executing that every single time the function is called!

1 Answers1

2

The problem is that, you are assigning the variable img before even loading the DOM.

var img = document.getElementById("theimage");

If you place/wrap all of your code with onload function of window, the problem should resolve since the onload makes sure that the DOM load.

window.onload = function(){

 var img = document.getElementById("theimage");

  ... your functions ()..

}

It is working when you place in function because, by the time you executing the function the DOM got loaded.

Suresh Atta
  • 114,879
  • 36
  • 179
  • 284