user3627265
user3627265

Reputation: 191

Adding a class while dynamically on slider

I'm trying to create a slider, it moves to the right when going to the next image. It also has a function where in it can move to specific image I used a ul li html for this

$('#right, #left').on('click', function () {
    slide($(this).attr('id'), 600);
    $('ul#slide-menu').find('li.active').removeClass( 'active' );
    $('ul#slide-menu').addClass( 'active' );
});

when the user click the li, it will have a class called "active" the color of li will change indicating that it is the current image chosen. The problem is that when the slider is automatically moving the function for indicating which image is not working.

This is how my slider moves

setInterval(function() {
    slide("right", 600);
}, 5000);

I tried to make it this way, but it only removed the class "active" but it is not adding. Any idea on this"?

setInterval(function() {
    slide("right", 600);
    $('ul#slide-menu').find('li.active').removeClass( 'active' );
    $('ul#slide-menu').addClass( 'active' );
}, 5000);

Here is the jsFiddle. There is a ul li at the bottom, I'm trying to make it also move indicating which image is being displayed.

Upvotes: 1

Views: 1652

Answers (1)

Canser Yanbakan
Canser Yanbakan

Reputation: 3870

You are adding active class to your ul#slide-menu. Not to the child li element... You can achieve this like;

$('ul#slide-menu').find('li:visible:first').addClass('active');

Edit:

var $slider = $('ul#slide-menu');
var $current = $slider.find('li.active');
var $next = $current.next();

if(!$next.length) {
    $next = $slider.find('li:first');
}

$current.removeClass('active');
$next.addClass('active');

JS Fiddle with new code:

http://jsfiddle.net/Lb9xg/

function slider() {
    var $slider = $('ul#slide-menu');
    var $current = $slider.find('li.active');

    if(!$current.length) {
        var $next = $slider.find('li:first');
    } else {
        var $next = $current.next();
        $current.removeClass('active');
    }

    if(!$next.length) {
        $next = $slider.find('li:first');
    }

    $next.addClass('active'); 
}

$(function(){
    setInterval(function(){slider();}, 1000);
});

Upvotes: 1

Related Questions