Search code examples
javascriptjqueryslidercarouseljssor

How to pick random few slides for jssor slider and hide the rest?


I have 8 slides and I want to show random 3 every time user refresh the page. How do I achieve this?


Solution

  • I decided to put the slides in another div and hide it. Then using solution from: jQuery select random elements with same class, I slice 3 of the div and then duplicate it into the jssor slide.

    function shuffle(array) {
      var m = array.length, t, i;
    
      // While there remain elements to shuffle…
      while (m) {
    
      // Pick a remaining element…
      i = Math.floor(Math.random() * m--);
    
      // And swap it with the current element.
      t = array[m];
      array[m] = array[i];
      array[i] = t;
      }
    
      return array;
    }
    
    jQuery(document).ready(function ($) {
        var $all = $(".all-slides > div").removeClass("selected");
        $(shuffle($all).slice(0, 3)).addClass("selected");
        $( ".selected" ).appendTo( ".slides" );
            var options = {
                $DragOrientation: 0,                                //[Optional] Orientation to drag slide, 0 no drag, 1 horizental, 2 vertical, 3 either, default value is 1 (Note that the $DragOrientation should be the same as $PlayOrientation when $DisplayPieces is greater than 1, or parking position is not 0)
                $ArrowNavigatorOptions: {                       //[Optional] Options to specify and enable arrow navigator or not
                    $Class: $JssorArrowNavigator$,              //[Requried] Class to create arrow navigator instance
                    $ChanceToShow: 2,                               //[Required] 0 Never, 1 Mouse Over, 2 Always
                    $AutoCenter: 0,                                 //[Optional] Auto center arrows in parent container, 0 No, 1 Horizontal, 2 Vertical, 3 Both, default value is 0
                    $Steps: 1                                       //[Optional] Steps to go for each navigation request, default value is 1
                }
            };
    
            var jssor_slider1 = new $JssorSlider$("slider_container", options);
    });