Search code examples
javascriptjqueryowl-carousel

How to stop Owl Carousel when clicking navigation arrows


I have a simple Owl carousel with autoplay set and navigation arrows, defined with the options below:

 var options = {
    mainBanner: {
        animateOut: 'fadeOut',
        autoplay: true,
        autoplayHoverPause: false,
        autoplaySpeed: 1200,
        dots: false,
        lazyLoad: true,
        loop: true,
        mouseDrag: false,
        pullDrag: false,
        touchDrag: false,
        nav: true,
        navText: [
            "‹",
            "›"
        ]
    },

...

When the user clicks the navigation arrow, I want it to stop autoplay. In order to do this, I added the following function:

setTimeout(function () {    
    $('.owl-nav > div').on('click', function () {
        $('.owl-carousel').trigger('stop.owl.autoplay');            
    })
}, 500);

(I added the timeout because the .owl-nav elements are not rendered yet when this function is loaded. It's not quite elegant, but it serves the purpose).

The problem is that when I click the navigation arrows, the autoplay stops. BUT, if I click them again (and again, and again), the slider keeps autoplaying. This is not the expected behaviour - I would simply like it to stop from the first click.

Any hints on how to solve this are very much appreciated. Thank you!


Solution

  • from what i gathered here and here it seems that it's a timer issue: triggering stop.owl.autoplay will destroy the timer, but not change the autoplay settings, so the timer is set again. You have to turn off (and back on if you want to re-activate) in the settings.

    you can try:

    $('.owl-nav > div').on('click', function () {
        $('.owl-carousel').trigger('stop.owl.autoplay');
    
        //simple one (EDIT: not enough to make it work after testing it):
        //$('.owl-carousel').trigger('changeOption.owl.carousel', { autoplay: false });
    
        //or more complicated (will work for one carousel only, or else use 'each'):
        //EDIT: this one seems to work
        var carousel = $('.owl-carousel').data('owl.carousel');
        carousel.settings.autoplay = false; //don't know if both are necessary
        carousel.options.autoplay = false;
        $('.owl-carousel').trigger('refresh.owl.carousel');
    });
    

    EDIT: the second solution seems to be working: https://jsfiddle.net/b6x6vc8q/3/