How to make Bootstrap carousel slider use mobile left/right swipe
I needed to add this functionality to a project I was working on recently and adding jQuery Mobile just to solve this problem seemed like overkill, so I came up with a solution and put it on github: bcSwipe (Bootstrap Carousel Swipe).
It's a lightweight jQuery plugin (~600 bytes minified vs jQuery Mobile touch events at 8kb), and it's been tested on Android and iOS.
This is how you use it:
$('.carousel').bcSwipe({ threshold: 50 });
I'm a bit late to the party, but here's a bit of jQuery I've been using:
$('.carousel').on('touchstart', function(event){
const xClick = event.originalEvent.touches[0].pageX;
$(this).one('touchmove', function(event){
const xMove = event.originalEvent.touches[0].pageX;
const sensitivityInPx = 5;
if( Math.floor(xClick - xMove) > sensitivityInPx ){
$(this).carousel('next');
}
else if( Math.floor(xClick - xMove) < -sensitivityInPx ){
$(this).carousel('prev');
}
});
$(this).on('touchend', function(){
$(this).off('touchmove');
});
});
No need for jQuery mobile or any other plugins. If you need to adjust the sensitivity of the swipe adjust the 5
and -5
. Hope this helps someone.
UPDATE:
I came up with this solution when I was pretty new to web design. Now that I am older and wiser, the answer Liam gave seems to be a better option. See the next top answer; it is a more productive solution.
I worked on a project recently and this example worked perfectly. I am giving you the link below.
First you have to add jQuery mobile:
http://jquerymobile.com/
This adds the touch functionality, and then you just have to make events such as swipe:
<script>
$(document).ready(function() {
$("#myCarousel").swiperight(function() {
$(this).carousel('prev');
});
$("#myCarousel").swipeleft(function() {
$(this).carousel('next');
});
});
</script>
The link is below, where you can find the tutorial I used:
http://lazcreative.com/blog/how-to/how-to-adding-swipe-support-to-bootstraps-carousel/