BootstrapHTMLJavaScriptjQueryWooCommerce

How to enable mouse swipe or drag on bootstrap carousel

0
4.7k
2018 / 11 / 29

The bootstrap carousel doesn’t comes with the swipe by default, this feature is not so good for mobile users. You can achieve swipe by adding a trick that will hook-in the swipe feature in carousel.

You have to use touchSwipe library. The CDN for touchSwipe is:

https//cdnjs.cloudflare.com/ajax/libs/jquery.touchswipe/1.6.4/jquery.touchSwipe.min.js

Use the following code:

<!-- swipe start -->
<script src='//cdnjs.cloudflare.com/ajax/libs/jquery.touchswipe/1.6.4/jquery.touchSwipe.min.js'></script>
<script type="text/javascript">
    $(".carousel").swipe({
        swipe: function (event, direction, distance, duration, fingerCount, fingerData) {
            if (direction == 'left') $(this).carousel('next');
            if (direction == 'right') $(this).carousel('prev');
        },
        allowPageScroll: "vertical" 
    });
</script>
<!-- swipe end -->

WordPress solution

If you uses custom coded bootstrap based theme for your WordPress website and you are using Bootstrap Carousel than you can enable the swipe on it by placing the following code in the footer.php file:

<!-- swipe start -->
<script src='//cdnjs.cloudflare.com/ajax/libs/jquery.touchswipe/1.6.4/jquery.touchSwipe.min.js'></script>
<script type="text/javascript">
    jQuery(".carousel").swipe({
        swipe: function (event, direction, distance, duration, fingerCount, fingerData) {
            if (direction == 'left') jQuery(this).carousel('next');
            if (direction == 'right') jQuery(this).carousel('prev');
        },
        allowPageScroll: "vertical" 
    });
</script>
<!-- swipe end -->

Note that the difference is with the $ sign with jQuery.

 

Note

You must add the CDN for touchSwipe after initializing jQuery JS and Bootstrap JS. So the sequence will be:

  1. jQuery JS
  2. Bootstrap JS
  3. touchSwipe JS

Hi, I am a full-stack web developer with 5+ years of experience in working with different web technologies. Do you want to ask something? just send me a message through the contact form. Please visit my portfolio at hamzamehmood.com. Thanks