I built a testimonial slider that automatically plays on load and stops auto playing when the slider controls are used to change the active slide.
I feel like it could be optimized easily, especially the adding and removing active class seems like it could be made better but I'm not sure how.
$(document).ready(function(){
// Check var to see if slider controls has been clicked
var clickedSlider = false;
// Automatically change the active Testimonial Slide
function autoSlide(){
// Get active Slide en corresponding Control item
var activeSlide = $('.testimonial-slider-slides a.active');
var activeControl = $('.testimonial-slider-controls a.active');
// If last testimonial is active start back from the beginning
if(activeSlide.is(':last-child')){
activeSlide.removeClass('active');
activeControl.removeClass('active');
$('.testimonial-slider-slides a').first().addClass('active');
$('.testimonial-slider-controls a').first().addClass('active');
} else {
// Else go to next slide
activeSlide.removeClass('active');
activeControl.removeClass('active');
activeSlide.next().addClass('active');
activeControl.next().addClass('active');
}
}
// If controls haven't been clicked, autoplay the slider
window.setInterval(function(){
if (clickedSlider === false) {
autoSlide();
}
}, 2000);
// Show corresponding slide when clicking on slider control
$('.testimonial-slider-controls a').click(function(e){
e.preventDefault();
clickedSlider = true;
$('.testimonial-slider-controls a.active').removeClass('active');
$(this).addClass('active');
var slide = ($(this).data('for'));
$('.testimonial-slider-slides a').removeClass('active');
$('[data-id="' + slide + '"]').addClass('active');
});
});
Any thoughts on this?
Update: This is the HTML I use:
<div class="testimonial-slider">
<div class="testimonial-slider-slides">
<div class="testimonial-slider-slides-slide active" data-id="1">
<!-- Slide content -->
</div>
<!-- extra slides -->
</div>
<div class="testimonial-slider-controls">
<a href="#" data-for="1" class="active">Slide 1</a>
<a href="#" data-for="2">Slide 2</a>
<a href="#" data-for="3">Slide 3</a>
</div>
</div>
This was updated after i first posted here but the only real change in the javascript / jquery is the slides are now selected by .testimonial-slider-slides-slide
instead of .testimonial-slider-slides a
Thanks to Mike Brant's Answer the data-for
and data-id
attributes can be left out