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/
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With