How can I determine whether the carousel is sliding left or right? I've looked at the documentation for the events slid and slide, but neither provide any relevant information on the direction of the slide.
I've also examined the event object that gets passed to the event handler for the slid event, but I can't seem to find any useful clues there either.
Any help would be appreciated!
As of 3.0.0-rc1, the following works to access active element, next element, from index, to index, and slide direction. Feel free to decrease specificity of your selectors as needed.
carousel.on('slide.bs.carousel', function (event) {
var active = $(event.target).find('.carousel-inner > .item.active');
var from = active.index();
var next = $(event.relatedTarget);
var to = next.index();
var direction = event.direction;
});
So as far as I can see twitter bootstrap doesn't expose what direction the carousel is moving via the event object. However, it DOES add a "right" or "left" class to elements involved in the slide.
So basically i see 2 options. Expose the direction in the event object or look for the right or left class on the elements.
Option 1:
You will have to modify the bootstrap carousel code. In the carousel, slide function change:
e = $.Event('slide')
to
e = $.Event('slide', {direction: direction})
(around line 337-340 in the normal version of bootstrap.js)
and then you can get the direction with something like this:
var $carousel = $('.carousel');
$carousel.carousel();
$carousel.bind('slide', function(e) {
console.log("e.direction = " + e.direction);
});
OR Option2:
Wait some time for the css "left" or "right" class to be added to the element and then check if that class is present.
var $carousel = $('.carousel');
$carousel.carousel();
$carousel.bind('slide', function(e) {
setTimeout( function(){
var left = $carousel.find('.item.active.left');
var right = $carousel.find('.item.active.right');
if(left.length > 0) {
console.log('left');
}
else if(right.length > 0) {
console.log('right');
}
}, 500);
});
Need the timeout because there is a race condition between when the event is triggered and when the left right classes are set. Obviously this is a hackyer solution, but you don't have to modify the bootstrap code. There are probably other options too, but i feel option 1 is the best.
Edit: In the latest version of bootstrap css (2.1.1) The line change for option 1 would be:
(line 340) from:
, e = $.Event('slide', {
relatedTarget: $next[0]
})
to:
, e = $.Event('slide', {
relatedTarget: $next[0],
direction: direction
});
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