9

Is there a way in Owl Carousel 2 make a king random function. I need the slides on the page to load randomly.

Before in the older Owl Carousel version I did it this way:

$(document).ready(function () {

    //Sort random function
    function random(owlSelector) {
        owlSelector.children().sort(function () {
            return Math.round(Math.random()) - 0.5;
        }).each(function () {
            $(this).appendTo(owlSelector);
        });
    }

    $(".feedback").owlCarousel({
        autoPlay: 5000,
        slideSpeed: 200,
        items: 1,
        itemsDesktop: [1199, 1],
        itemsDesktopSmall: [979, 1],
        itemsTablet: [768, 1],
        itemsMobile: [479, 1],
        autoHeight: true,

        //Call beforeInit callback, elem parameter point to $(".feedback")
        beforeInit: function (elem) {
            random(elem);
        }
    });
});

How can this be done in the best way in Owl Carousel 2?

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
del mar
  • 91
  • 1
  • 3

3 Answers3

20

You have to use the new onInitialize callback, like this:

var owl = $('.owl-carousel');
owl.owlCarousel({
    onInitialize : function(element){
        owl.children().sort(function(){
            return Math.round(Math.random()) - 0.5;
        }).each(function(){
            $(this).appendTo(owl);
        });
    },
});

Find more information in the 2.x docs.

insertusernamehere
  • 23,204
  • 9
  • 87
  • 126
AdmireNL
  • 396
  • 1
  • 9
2

For some reason, AdmireNL's answer was giving me problems for iOS devices but worked perfectly for everything else. No idea why that would be, but I solved my issue by using the top answer listed here: How to randomly sort list items?

My final code:

$.fn.randomize = function(selector){
  var $elems = selector ? $(this).find(selector) : $(this).children(),
  $parents = $elems.parent();

  $parents.each(function(){
    $(this).children(selector).sort(function(){
        return Math.round(Math.random()) - 0.5;
    }).detach().appendTo(this);
  });

  return this;
};

var slider = $('#slider');
slider.owlCarousel({
    onInitialize : function(){
        $(slider).randomize();
    }
});
Dtrav
  • 355
  • 1
  • 2
  • 14
0

I could not get this to work for the life of me so what I did instead was randomize the imgs in the carousel in my html with this JS function prior to my carousel JS code. Randomizer code I found on stackoverflow:

let ul = document.querySelector('#slider');
for (var i = ul.children.length; i >= 0; i--) {
  ul.
appendChild(ul.children[Math.random() * i | 0]);
}
Tyler2P
  • 2,324
  • 26
  • 22
  • 31
worstDev
  • 17
  • 5