I have a carousel slider, which have three static “dots” in the corner, one for each slide.
When the slide is active, the corresponding dot is white. When inactive, the dot is grey.
I have made this possible with this code below, but Im new to Jquery so Im looking if this can be shortened.
Is it possible to rewrite this code to be shorter?
I have this in the HTML:
<a id="th_1" class="thumb act"></a>
<a id="th_2" class="thumb"></a>
<a id="th_3" class="thumb"> </a>
Then I have this in jquery, at the top of the document:
$(document).ready(function(){
$('#th_1').click(function(){
$('#carousel').carousel(0); //go to slide1
$('#th_1').addClass('act');
$('#th_2').removeClass('act');
$('#th_3').removeClass('act');
;})
$('#th_2').click(function(){
$('#carousel').carousel(1); //go to slide 2
$('#th_1').removeClass('act');
$('#th_2').addClass('act');
$('#th_3').removeClass('act');
;})
$('#th_3').click(function(){
$('#carousel').carousel(2); //go to slide 3
$('#th_1').removeClass('act');
$('#th_2').removeClass('act');
$('#th_3').addClass('act');
;})
Then, I also have this below code for when the slides are rotating themselves, without clicks (because I need to change the dots when this happens as well).
$('#carousel_slide_1').hasClass('active')(function(){
$('#th_1').addClass('act');
$('#th_2').removeClass('act');
$('#th_3').removeClass('act');
});
$('#carousel_slide_2').hasClass('active')(function(){
$('#th_1').removeClass('act');
$('#th_2').addClass('act');
$('#th_3').removeClass('act');
});
$('#carousel_slide_3').hasClass('active')(function(){
$('#th_1').removeClass('act');
$('#th_2').removeClass('act');
$('#th_3').addClass('act');
});
The class “active” is on a div, which contains the slide. When the slide is active, this class is added through another carousel script to the div. So above I check if the div has this class, and if so, I change the class of the “dot”.
The class “act” is simply a background change of the “dot” which makes it white in color, if the class is set. If removed, color of dot is grey.
Hope I haven’t forgotten anything. If so, I will update this question.
Thanks
For the first piece of code you can just use the
index()function and a generic class likethumbas you have.The second piece of code doesn’t seem right for what you’re trying to do. The idea is to create a function or object to handle these events where you can pass values and the you just call those functions within the jQuery event. I hope this makes sense.
I wrote a tutorial a while ago on how to create a slider in jQuery, it might be useful.
http://www.onextrapixel.com/2011/07/01/how-to-create-a-slideshow-plugin-with-jquery/