Pxion Pxion - 2 months ago 9x
Javascript Question

Image slider is not working

I have done an image slider but this is not changing the images, just showing the first image.

This is my javascript

$(document).ready(function() {
var slides = document.querySelectorAll('#images .image');
var current = 0;

function nextImage() {
image[currentSlide].className = 'slide';
current = (current+1)%images.length;
images[current].className = 'image show';
var Interval = setInterval(nextImage,2000);


<ul id="images">
<li class="image show">Slide 1</li>
<li class="image">Slide 2</li>
<li class="image">Slide 3</li>
<li class="image">Slide 4</li>
<li class="image">Slide 5</li>

I am using jquery 3.1.0 and it is not working

Lew Lew

I have checked your code and it seems to work fine, apart from the unecessary call to nextSlide() near the end of document ready. Perhaps it's your CSS? Please run this working code snippet:

$(document).ready(function() {
	var slides = $('#slides .slide');
	var currentSlide = 0;
	var slideInterval = setInterval(nextSlide, 2000);

	function nextSlide() {
		currentSlide = (currentSlide + 1) % slides.length;
.slide {display:none;}
.showing {display:block;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
<ul id="slides">
    <li class="slide showing">Slide 1</li>
    <li class="slide">Slide 2</li>
    <li class="slide">Slide 3</li>
    <li class="slide">Slide 4</li>
    <li class="slide">Slide 5</li>

I have removed mixed vanilla JS and used jQuery to keep things more consistent.

Some other things to check as the Javascript may not be running at all:

  • Check for errors in the console
  • Check you are linking jQuery properly (before your code, script tags parsed and executed from top to bottom in order unless you specify otherwise)
  • Make sure you have only one $(document).ready per page.