0

I have two images with different classes but I want the same JavaScript to be applied to both. This javascript basically allows for a slideshow by clicking on the button, but this only works for the images with the mySlides class, not the albums class. Take a look:

var slideIndex = 1;
showDivs(slideIndex);

function plusDivs(n) {
  showDivs(slideIndex += n);
}

function showDivs(n) {
  var i;
  var x = document.querySelectorAll(".mySlides, .albums");
  if (n > x.length) {
    slideIndex = 1
  }
  if (n < 1) {
    slideIndex = x.length
  };
  for (i = 0; i < x.length; i++) {
    x[i].style.display = "none";
  }
  x[slideIndex - 1].style.display = "block";
}
<link href="https://www.w3schools.com/w3css/4/w3.css" rel="stylesheet"/>
<div class="inner">
  <img class="mySlides" src="./imgs/IMG_1552.JPG">
  <img class="mySlides" src="./imgs/IMG_0915.jpg">
  <button class="w3-button w3-display-left" onclick="plusDivs(-1)">&#10094;</button>
  <button class="w3-button w3-display-right" onclick="plusDivs(+1)">&#10095;</button>
</div>

<div class="inner">
  <img class="albums" src="./imgs/travis.jpg">
  <img class="albums" src="./imgs/killy.jpg">
  <button class="w3-button w3-display-left" onclick="plusDivs(-1)">&#10094;</button>
  <button class="w3-button w3-display-right" onclick="plusDivs(+1)">&#10095;</button>
</div>

The buttons are supposed to move to the next image eg from "travis.jpg" to "killy.jpg" but it only works for the mySlides class and not the albums class

Chayim Friedman
  • 47,971
  • 5
  • 48
  • 77
KSekhar
  • 15
  • 3
  • Your code [seems to work fine](https://jsfiddle.net/j9carb63/1/) ..? – Teemu Jan 26 '21 at 19:45
  • 1
    I would use ```querySelectorAll``` to target a different selector. If it's more global than just selecting a class, then choose a global selector! For example if you want to target ```img``` tags, your code would be like this: ```querySelectorAll("div.inner img")``` and it'll select all of the images for you regardless of their classes. – Ruvee Jan 26 '21 at 21:04

1 Answers1

0

The issue lies in var x = document.querySelectorAll(".mySlides, .albums"); As you have to understand that this query selects all the 4 elements if you want to do for the second element of both classes you would have to go with

var x = document.querySelectorAll(".mySlides");
var y = document.querySelectorAll(" .albums");

and run the further logic on both var seperately

  • 1
    "_this query selects all the 4 elements_" Yes, that is OP's purpose, and that's what the code does, though OP says the code doesn't include `albums` class in the slides. – Teemu Jan 26 '21 at 20:10