Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

add class 'active' to current control

Tags:

jquery

I use a simple jquery fade slider on my page

HTML

<ul id="slider1" class="images-list">
                        <li style="background-image: url('Content/img/bg_10.jpg')"></li>
                        <li style="background-image: url('Content/img/bg_11.jpg')"></li>
                        <li style="background-image: url('Content/img/bg_12.jpg')"></li>
                    </ul>

                    <ul class="controls">
                        <li class="active"></li>
                        <li></li>
                        <li></li>
                    </ul>

jQuery

    $.fn.slider = function () {
    var $this = this;
    var $controls = $this.nextAll('.controls').first();
    var index;

    $this.find('li:gt(0)').hide();
    setInterval(function () {
        $this.find('li:first-child').fadeOut('slow')
            .next('li').fadeIn('slow')
            .end().appendTo($this);

        $controls.find('li').removeClass('active');         
        index = $this.find('li:visible').index();
        $controls.find('li').eq(index).addClass('active');  
    },
    4000);
};

and I would like to add class 'active' to current control, but a position of a visible element in slider changes every time and it's the first element every time. How can I do that?

http://jsfiddle.net/u9d3xa1q/11/

like image 992
truslivii.lev Avatar asked Mar 03 '26 21:03

truslivii.lev


1 Answers

Probably you can utilize the jquery.next() and jquery.prev() methods. Initially set the class to the first element in controls. And then:

//on next:
$controls.find('li.active').removeClass('active').next('li').addClass('active');  
//on prev:
$controls.find('li.active').removeClass('active').prev('li').addClass('active');

Probably if you need an infinite sliding the above will need to change. Here is the code to match your current fiddle:

            if ($controls.find('li.active').next('li').length) {
            $controls.find('li.active').removeClass('active').next('li').addClass('active');
        } else {
            $controls.find('li.active').removeClass('active').parent().find('li:first-child').addClass('active');
        }

fiddle

Edit

Here is a fiddle with data attribute usage as per the comments.

like image 102
mzografski Avatar answered Mar 05 '26 12:03

mzografski