ThisIsNotArmand
ThisIsNotArmand

Reputation: 99

Javascript slider errors in console and not sliding

The page works fine, but the slider doesn't slide to the next image. JSFiddle makes it work out fine and the images slide, yet on localhost or any live website it fails.

<script>

    var slides = document.querySelectorAll('#slides.klant');
var currentSlide = 0;
var slideInterval = setInterval(nextSlide,2000);

function nextSlide(){
    slides[currentSlide].className = 'klant';
    currentSlide = (currentSlide+1)%slides.length;
    slides[currentSlide].className = 'klant showing';
}


</script>

<title>Untitled Document</title>
</head>

<body>

<div id="ads">
<ul id="slides">
    <li class="klant showing"><img src="img/first.jpg"></li>
    <li class="klant"><img src="img/second.jpg"></li>
    <li class="klant"><img src="img/third.jpg"></li>
    <li class="klant"><img src="img/fourth.jpg"></li>
    <li class="klant"><img src="img/fifth.jpg"></li>
</ul>
</div>

I get an error "Uncaught TypeError: Cannot set property 'className' of undefined" on the slides[currentSlide].className = 'klant'; part of the function but can't figure out what's going wrong.

Upvotes: 2

Views: 253

Answers (3)

Oluwafemi
Oluwafemi

Reputation: 14889

With input from Teemu(see comments below), the major issue is that your script is loaded before the HTML. Thus, the elements are undefined at the point the script ran. Wrapping the script in an onload event should solve the problem and putting a space between #slides and .klant in your script. See below example:

<script>

window.onload = function () {
   var slides = document.querySelectorAll('#slides .klant');
   var currentSlide = 0;
   var slideInterval = setInterval(nextSlide,2000);


function nextSlide(){
        slides[currentSlide].className = 'klant';
        currentSlide = (currentSlide+1)%slides.length;
        slides[currentSlide].className = 'klant showing';
    }

 }

</script>

Upvotes: 1

user1363245
user1363245

Reputation:

Just Replace
 line var slides = document.querySelectorAll('#slides.klant');

with

    var sliderparent = document.getElementById('slides');
var slides = sliderparent.querySelectorAll('.klant');

Upvotes: 1

O_Z
O_Z

Reputation: 1563

the script executes before the page finished loading, so the querySelectorAll returns an empty array. copy your script to the end of the <body> and it will work fine.

On JsFiddle it works because by default script executes there after load.

Upvotes: 1

Related Questions