0

I am trying to create a simple jquery slideshow. However I am having trouble getting it to loop through the elements.

I know next() just add's the active class to the next elements, and not a single. That is the part i am having trouble with. How can just apply a single class to the next element, and it loop forever.

jQuery(document).ready(function () {

var slides = jQuery('#slideshow'); //Parent container for the slideshow
var activeClass = 'active'; //Set the active slide CSS class
var interval = 3000; // Interval in miliseconds
var countSlides = slides.children().length;

//Runs the slideshow
function cycle() {
    slides.children().removeClass(activeClass);
    slides.children().next().addClass(activeClass);
};

setInterval(cycle, interval);
});

1 Answer 1

2

According to the documentation .next() returns the element next to every element in the collection it is called on. In your case that is all children. If you select only the current active element before dropping the .active class you can get the element next to it.

function cycle() {
    var $current = slides.children('.active');
    $current
        .removeClass('active')
        .next().addClass('active');
}

Edit: as on how to loop. You need to check if there is a next element. If .next() does not return a new element you could grab the first child instead:

var $current = slides.children('.active'),
    $next = $current.next();
if (!$next.length) {
   // No next slide, go back to the first one.
   $next = slides.children().first();
}
$current.removeClass('active');
$next.addClass('active');
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. That worked great! Any suggestions on getting it to loop?

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.