Difference between declaring var inside function and outside

Hi,
I worked on a simple image slide-show with javascript, and I assigned a value to a var outside of a function using getElementById() like this:


window.onload = initLinks;
    
    myImg = new Array("images/img01.jpg","images/img02.jpg","images/img03.jpg","images/img04.jpg");
    curPic = 0;
    theImg = document.getElementById("slideshowImg");
    
    function initLinks(){
    	document.getElementById("nextLink").onclick = nextImg;
    	document.getElementById("prevLink").onclick = prevImg;
    }

It didn’t work, so I moved the statement into the function:


window.onload = initLinks;

myImg = new Array("images/img01.jpg","images/img02.jpg","images/img03.jpg","images/img04.jpg");
curPic = 0;

function initLinks(){
	theImg = document.getElementById("slideshowImg");
	
	document.getElementById("nextLink").onclick = nextImg;
	document.getElementById("prevLink").onclick = prevImg;
}

Please explain the difference.

I also tried assigning the source of the image to theImg var like this:

theImg = document.getElementById("slideshowImg").src;

and when I tried to use it later:

theImg = myImg[curPic]

it didn’t work.

So instead I did:

theImg = document.getElementById("slideshowImg");

and

theImg.src = myImg[curPic]

What is the difference between those statement? It looks very similar.

Thanks in advance.

I think that the statement:

theImg = document.getElementById("slideshowImg"); 

didn’t work outside the function is because it was being executed before the loading of the DOM and therefore before the loading of the image: slideshowImg. So there was no image to select because the image element hadn’t loaded yet.

When you placed it inside the function initLinks() , you made sure that the statement is executed after the image:slideshowImg was loaded. That is because initLinks() is called after the onload event (window.onload = initLinks)

As for assigning the source, when you use the statement:

theImg = document.getElementById("slideshowImg").src;

theImg variable will simply contain a string copy of the image’s source and when you change it, it has nothing to do with the actual image.

When you changed the statement to :

theImg = document.getElementById("slideshowImg");

theImg variable now contained a reference to the object which is the image element. Any changes to this variable will directly affect the image element in your DOM.

Very helpful,
thanks!