Javascript Question

Local vs. global variables in javascript

I'm very new to coding and i'm trying to understand the difference between local and global variables. I was trying to create an image gallery where you could switch image by pressing buttons. I got it to work by putting the image variables inside the functions as a local variables. But if i put it outside of the function as one, global variable it wouldn't work. Why is that?

Here is my html:

<button onclick="previous_image();"></button>
<img src="image1.jpg" alt="Image gallery" id="image"/>
<button onclick="next_image();"></button>


Here is my Javascript when i got it to work:

var image_tracker = "a";

function previous_image(){
var image = document.getElementById("image");
switch(image_tracker){
case("a"):
image.src = "image3.jpg";
image_tracker = "c";
break;

case("c"):
image.src = "image2.jpg";
image_tracker = "b";
break;

case("b"):
image.src = "image1.jpg";
image_tracker = "a";
break;
}

}

function next(){
var image = document.getElementById("image");
switch(image_tracker){
case("a"):
image.src = "image2.jpg";
image_tracker = "b";
break;

case("b"):
image.src = "image3.jpg";
image_tracker = "c";
break;

case("c"):
image.src = "image1.jpg";
image_tracker = "a";
break;
}

}


Here is my javascript when it didn't work:

var image_tracker = "a";
var image = document.getElementById("image");

function previous_image(){
switch(image_tracker){
case("a"):
image.src = "image3.jpg";
image_tracker = "c";
break;

case("c"):
image.src = "image2.jpg";
image_tracker = "b";
break;

case("b"):
image.src = "image1.jpg";
image_tracker = "a";
break;
}

}

function next(){
switch(image_tracker){
case("a"):
image.src = "image2.jpg";
image_tracker = "b";
break;

case("b"):
image.src = "image3.jpg";
image_tracker = "c";
break;

case("c"):
image.src = "image1.jpg";
image_tracker = "a";
break;
}

}

Answer

Use something like this:

window.onload = function() {
  var image = document.getElementById("image");
};
Comments