简体   繁体   中英

Add active class to 2 Bootstrap Carousels on same page with Jquery

I have 2 bootstrap carousels on 1 page (special-carousel and quote-carousel). Neither carousel has any active classes set as I want to set them with javascript. My javascript code works for the first carousel but not the 2nd. Both carousels use different ID's and I have tried duplicating the javascript code to target just the 2nd carousel but the slides do not display.

The first item within the second slider has 2 new classes added to it which are next left which are obviously wrong.

My javascript looks like this:

<!-- Code for special carousel -->
<script>
    jQuery(document).ready(function() {
        $(".carousel-indicators li:first").addClass("active");
        $(".carousel-inner .item:first").addClass("active");
    });
</script>
<!-- Code for quote carousel -->
<script>
    (document).ready(function() {
        $(".carousel-indicators li:first").addClass("active");
        $(".carousel-inner .item:first").addClass("active");
    });
</script>

I've setup a demo page that shows the problem http://handcoded.co.uk/carousel.html

How can I target the 2nd carousel so that active classes are added to it?

The problem is in your javascript code, your jquery selector are targeting the same carousel instance. You should narrow your selector like that :

<!-- Code for special carousel -->
<script>
$(document).ready(function(){
  $("#special-carousel .carousel-indicators li:first").addClass("active");
  $("#special-carousel .carousel-inner .item:first").addClass("active");
});
</script>

<!-- Code for quote carousel -->
<script>
$(document).ready(function(){
  $("#quote-carousel .carousel-indicators li:first").addClass("active");
  $("#quote-carousel .carousel-inner .item:first").addClass("active");
});
</script>

link to working fiddle : https://jsfiddle.net/DTcHh/11116/

Mind that there is some possible enhancement to your code, for eg you can use only one document ready, cache jquery selector, etc

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM