Chris 2pha Brown. Drupal developer Brisbane Australia

Chris Brown

Drupal, Javascript, Three.js, 3D

website blog
image for Javascript snippet for "jump to" functionality in Owl Carousel

Javascript snippet for "jump to" functionality in Owl Carousel

Putting this here for my own future reference.
It adds an input textfield under an owl carousel (2.0.0-beta.2.4) to jump to a certain item.
Dots must be on to use the "to" method.
It also includes some stuff for lazy loading as it did not seem to work when using the "to" method of the OwlCarousel.

        var container = $('.view-collection-item-viewer-new .view-content', context);
        var carousel = container.owlCarousel({
          items: 2,
          lazyLoad: true,
          loop: false,
          nav: true,
          //dots: false,
          margin: 10,
          mouseDrag: false,
          responsive : {
            200 : {
              items: 2,
            },
            600 : {
              items: 3,
              //dots: true,
            },
            900 : {
              items: 4,
              //dots: true,
            }
          },
          callbacks: true,
          onInitialized: function(){
            var carousel = this;
            var jumpcon = $('<div class="owl-jump"/>');
            var jumpform = $('<form>go to page <input type="text"/></form>').submit(function(e){
              var num = e.target[0].value;
              if($.isNumeric(num) && num >= 1 && num <= carousel._items.length){
                try{
                  var oneachpage = carousel._items.length / carousel._plugins.navigation._pages.length;
                  var newpage = Math.ceil(num / Math.ceil(oneachpage));
                  carousel.to(newpage - 1);
                }catch(e){}
              }
              return false;
            });
            jumpform.append(' of '+carousel._items.length+' <input type="submit" value="Go">');
            jumpcon.append(jumpform);
            carousel.$element.find('.owl-controls').append(jumpcon);
          },
          onTranslated: function(){
            // Lazy loading doesn't work well when using owl carousel 'to' method, so we do it here manually after the transition has ended.
            var carousel = this;
            $('.owl-item', carousel.$element).each(function(index, element){
              if($(element).hasClass('active')){
                carousel._plugins.lazy.load(index);
              }
            });
          }
        });

Add a comment

<b>, <i> and <code> tags are allowed.