0

Ive been trying to create this certain slideshow for a webpage I am making. Everytime Im trying to replace the images with an id tag, the slideshow freezes at the first picture. I just want a way to use the same method to create a slide show using div ids (since Im trying to write/edit on the panels). If there is an another method, please mention it also.

This is the code I am using for the images:

var pic = document.getElementById("car");
var Array = ["images/pic_1.jpg", "images/pic_2.jpg", "images/pic_3.jpg"];
var index = 0;

function myFunction() {
  pic.setAttribute("src", Array[index]);
  index++;
  if (index >= Array.length) {
    index = 0;
  }
}

setInterval(myFunction, 1000);
fry01
  • 29
  • 7
  • 3
    probably not a good idea to use `Array` as a variable name since it's already a reserved word... – Jonathan.Brink Nov 22 '17 at 18:18
  • 2
    You're changing the `src` of a single ``. You can't use the exact same method to switch `
    `s. Instead you need to turn the `
    `s visible and invisible.
    –  Nov 22 '17 at 18:20
  • 1
    You aren't calling `setTimeout` after the first time, this means it will only change the image once. – Maluen Nov 22 '17 at 18:24
  • Why would you do `pic.setAttribute()` instead of simply `pic.src = ...` -- functionally should be similar, but https://stackoverflow.com/questions/3919291/when-to-use-setattribute-vs-attribute-in-javascript – Snowmonkey Nov 22 '17 at 18:26

2 Answers2

0

Actually, you can use some parts of code (and basic idea), and do something like this:

var index = 0;
slides=document.querySelectorAll('.slide');
function myFunction() {
for(i=0;i<slides.length;i++) {
slides[i].style.display='none'; //hide all
}
slides[index].style.display='block'; //show current
  index++;
  if (index >= slides.length) {
    index = 0;
  }
}

setInterval(myFunction, 1000);

DEMO:

var index = 0;
slides=document.querySelectorAll('.slide');
function myFunction() {
for(i=0;i<slides.length;i++) {
slides[i].style.display='none'; //hide all
}
slides[index].style.display='block'; //show current
  index++;
  if (index >= slides.length) {
    index = 0;
  }
}

setInterval(myFunction, 1000);
.slide {
  display:none;
  position:absolute;
}
<div id="container">


<div class="slide">
111111
</div>
<div class="slide">
222222222
</div>
<div class="slide">
333333333333
</div>
</div>
sinisake
  • 11,240
  • 2
  • 19
  • 27
-1

Don't call your Array an... Array because it's a keyword for JavaScript Array Object. Try something like that:

var cars = ["images/pic_1.jpg","images/pic_2.jpg","images/pic_3.jpg"]
(...)
pic.setAttribute("src" , cars[index])

It should help.

sofalse
  • 77
  • 1
  • 14