Convert inline javascript to external file

354 Views Asked by At

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

There are 1 best solutions below

0
Jack Bashford On

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);