-3

I am trying to write an image slider in Javascript, I was looking at examples online and found this particular one:

function slider(){
var current = 0;
slides = document.getElementsByClassName("images");
setInterval(function() {
for (var i = 0; i < slides.length; i++) {
    slides[i].style.opacity = 0;
}
current = (current != slides.length - 1) ? current + 1 : 0;
slides[current].style.opacity = 1;
}, 3000);
}
window.onload=slider;

I have tested this and it works with no errors.

I am wondering why the variable 'slides' is not declared as 'var slides', when I add 'var' the script stops working. Don't all variables in Javascript start with 'var'? why does this work without the 'var'?

  • 2
    Just [RTFM](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declaring_variables) – hindmost Apr 21 '16 at 12:27
  • It's a global variable then. – Bartek Banachewicz Apr 21 '16 at 12:28
  • This is global variable – The scion Apr 21 '16 at 12:28
  • 1
    I'm tempted to close this as a duplicate of [Declaring variables without var keyword](http://stackoverflow.com/questions/6888570/declaring-variables-without-var-keyword), although this question also asks about a specific situation. – apsillers Apr 21 '16 at 12:29
  • Are you sure that adding `var` makes it stop working? It should be fine - can you show a small snippet of where you've added it, along with in what way it's not working (any errors etc?) – James Thorpe Apr 21 '16 at 12:30

1 Answers1

0

Correctly declaring slides as var slides does not break this function.

Run the example below.

function slider() {
    var current = 0;
    var slides = document.getElementsByClassName("images");
    setInterval(function() {
       for (var i = 0; i < slides.length; i++) {
           slides[i].style.opacity = 0;
      }
      current = (current != slides.length - 1) ? current + 1 : 0;
      slides[current].style.opacity = 1;
    }, 3000);
}
window.onload=slider;
<div class="images">image1</div>
<div class="images">image2</div>
<div class="images">image3</div>
Martin
  • 15,820
  • 4
  • 47
  • 56