0

I am working on a carousel in w3school. They actually have an inline javascript code and I am trying to convert it to an external javascript file. I have this code in my external file

window.addEventListener('DOMContentLoaded', function () {
    var slideIndex = 1;
    showSlides(slideIndex);

    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";
    }
}, false);

But when I navigate the carousel, it displays error Uncaught ReferenceError: currentSlide is not defined at HTMLSpanElement.onclick and does not work/navigate the images in the carousel

This is the HTML code

<div class="slideshow">
  <div class="slideshow-container">
      <div class="mySlides fade">
        <img class="carousel-item" src="https://lorempixel.com/800/400/food/1">
      </div>
      <div class="mySlides fade">
        <img class="carousel-item" src="https://lorempixel.com/800/400/food/2">
      </div>
  </div>

  <div class="slide-nav">
      <span class="dot" onclick="currentSlide(1)"></span> 
      <span class="dot" onclick="currentSlide(2)"></span>
  </div>
</div>
<script type="text/javascript" src="js/components.js"></script>

1 Answer 1

1

Because currentSlide is not globally accessible (HTML inline event handlers run in the global scope). You need to define it in the global scope for it to work:

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

window.addEventListener("DOMContentLoaded", function() {...}, false);
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.