0

I have A global scope variable that is interfering with the rest of my code I want to be able to implement it within these 3 functions or to turn it all into 1 function that doesn't use global variables but I'm not sure how to achieve this can someone help me. Any help would be appreciated thank you.

var slideIndex = 1;
showSlides(slideIndex);

function plusSlides(n) {
  showSlides((slideIndex += n));
}

function currentSlide(n) {
  showSlides((slideIndex = n));
}

function showSlides(n) {
  var i;
  var slides = document.getElementsByClassName("mySlides");
  var dots = document.getElementsByClassName("dot");
  if (n > slides.length) {
    slideIndex = 1;
  }
  if (n < 1) {
    slideIndex = slides.length;
  }
  for (i = 0; i < slides.length; i++) {
    slides[i].style.display = "none";
  }
  for (i = 0; i < dots.length; i++) {
    dots[i].className = dots[i].className.replace(" active", "");
  }
  slides[slideIndex - 1].style.display = "block";
  dots[slideIndex - 1].className += " active";
}
<div>
  <a class="prev" onclick="plusSlides(-1)">&#10094;</a>
  <a class="next" onclick="plusSlides(1)">&#10095;</a>
</div>
<!-- slideshow-container -->
<div class="dot-container-for-slide-banner">
  <span class="dot" onclick="currentSlide(1)"></span>
  <span class="dot" onclick="currentSlide(2)"></span>
  <span class="dot" onclick="currentSlide(3)"></span>
  <span class="dot" onclick="currentSlide(4)"></span>
</div>
Miu
  • 846
  • 8
  • 22

1 Answers1

1

If you just put the whole code here inside an Immediately Invoked Function Expression (short IIFE), that should prevent any unnecessary global variables:

(() => {
  var slideIndex = 1;
  showSlides(slideIndex);

  // ...
})();

You should also absolutely avoid inline attribute handlers like

onclick="plusSlides(-1)"

and

onclick="currentSlide(1)"

because they require global pollution and have a demented scope chain. Attach the listeners properly using addEventListener instead:

document.querySelector('.prev').addEventListener('click', () => {
  plusSlides(-1);
});
document.querySelector('.next').addEventListener('click', () => {
  plusSlides(1);
});

document.querySelectorAll('.dot').forEach((span, i) => {
  span.addEventListener('click', () => {
    currentSlide(i + 1);
  });
});
CertainPerformance
  • 356,069
  • 52
  • 309
  • 320