3
\$\begingroup\$

I am using this jQuery code to get two carousels working in bootstrap, and it's working for me.

$('#image-gallery-carousel').carousel({
  interval: 5000
});

$('#carousel-caption-text').html($('#slide-content-0').html());


// When the carousel slides, auto update the text
$('#image-gallery-carousel').on('slid.bs.carousel', function (e) {
  var id = $(this).find('.item.active').data('slide-number');
  //alert(id);
  $('#carousel-caption-text').html($('#slide-content-'+id).html());
});


$('#video-gallery-carousel').carousel({
  interval: 12000
});

$('#carousel-caption-video-text').html($('#slide-content-0').html());


// When the carousel slides, auto update the text
$('#video-gallery-carousel').on('slid.bs.carousel', function (e) {
  var id = $(this).find('.item.active').data('slide-number');
  //alert(id);
  $('#carousel-caption-video-text').html($('#slide-content-'+id).html());
}); 

If there is any better way to implement this, please point it out to me.

\$\endgroup\$
3
  • \$\begingroup\$ Can I get a review for this code? \$\endgroup\$
    – user46791
    Jun 24, 2014 at 3:25
  • \$\begingroup\$ Can you include your HTML markup? A jsfiddle or jsbin with all of this would be very helpful too \$\endgroup\$
    – Larz
    Jul 2, 2014 at 20:43
  • \$\begingroup\$ Any one have demo link please share that is about adding video and image in a carousel? \$\endgroup\$
    – amjayesh07
    Nov 18, 2016 at 12:15

1 Answer 1

2
\$\begingroup\$

From a once over:

  • Magic constants should go on top ( 5000 and 12000
  • You use this construct .html($('#slide-content-'+id).html()); 4 times, a helper functions might be in order.
  • You don't need e in the event handling function, so you can just drop that
  • Image and video carousel use pretty much the same code, that could be a helper function as well.

So something like this potentially:

var imageCarouselSpeed = 5000,
    videoCarouselSpeed = 12000;

startCarousel( '#image-gallery-carousel', '#carousel-caption-text', imageCarouselSpeed );
startCarousel( '#video-gallery-carousel', '#carousel-caption-video-text', videoCarouselSpeed );

function startCarousel( carouselSelector, textSelector, speed ){
  //Start bootstrap carousel
  $( carouselSelector ).carousel({
    interval: speed
  });
  //Set the first caption
  $(textSelector).html($('#slide-content-0').html());
  // When the carousel slides, auto update the caption
  $(carouselSelector).on('slid.bs.carousel', function () {
    var id = $(this).find('.item.active').data('slide-number');
    $(textSelector).html($('#slide-content-'+id).html());
  });
}

I would agree with Larz a jsfiddle or jsbin would have gotten you a code review much sooner.

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.