Search code examples
javascripthtmlcssslideshow

What did I do wrong with this slide show code?


I've coded a very simple slide show, that shows a new slide every 5 seconds. The slide show image names are: 1.png, 2.png, 3.png, etc. There is a total of 5 slides. When I refresh my browser, the slide show doesn't work. For the record, I coded this with the help of w3schools.com and other tutorials, and I literaly copied the code from the sites(of course I changed the variables). Even though I did that, it still doesn't work. Pls help.

JS code(in ):

<script type="javascript">
  var number=0;
  function change_slide() {
    number++;
    if(number>5) {
      number=1;
    }
    document.getElementById( "slider" ).style.backgroundImage="url(number + '.png')";    
    setInterval(change_slide, 5000);
  }
</script>

in body tag:

<body onload="change_slide()">

slide show div

<div id="slider"></div>

slide show css

#slider {
  float:left;
  width:505px;
  height:330px;
  margin-right: 50px;
  margin-left: 25px;
  margin-top: 25px;
  border:2px solid black;
  border-radius: 15px;
}

Sorry for no code snippet, but the code of the site is to long.

PS.all slide show images all have dimentions of: 505x330 pixels.


Solution

  • you could consider changing your function to:

    <script>
    var number = 0;
    
    function change_slide() {
        number = ++number % 5;
        document.getElementById("slider").style.backgroundImage = ["url('", number, "'.png')"].join("");
        setTimeout(change_slide, 5000);
    }
    
    </script>
    

    This culprit line should be as pointed out by @Matt L.