Search code examples
javascriptjqueryhtmlcssowl-carousel

How to set the width responsively in owl-carousel?


Is there a way to specify .owlCarousel({ responsive:{ according to the width of .right?

I implement variable width for .left by jQuery UI Resizable.

So I want to change the number of sliding elements according to the width of .right.

Sample: https://jsfiddle.net/3mt7ykcs/

HTML:

<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.carousel.min.css" type="text/css" rel="stylesheet" />
<link href="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/assets/owl.theme.default.css" type="text/css" rel="stylesheet" />
<script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/OwlCarousel2/2.3.4/owl.carousel.min.js"></script>

<div class="flex">
  <div class="left">
    <p>.left is variable width by jQuery UI Resizable</p>
  </div>
  <div class="right">
    <p>I want to determine the number of slider elements according to the range of .right</p>
    <div id="owl-example" class="owl-carousel">
    </div>
  </div>  
</div>

CSS:

.flex {
    display: flex;
}
.right, .left {
    width: 50%;
    background: orange;
    margin: 10px;
    position: relative;
}

JS:

$(document).ready(function() {

    var img = '<div><img src="https://placehold.jp/150x150.png"></div>';
    for (var i = 0;  i < 10;  i++) {
        $("#owl-example").append(img);
    }

    $("#owl-example").owlCarousel({
        loop   : false,
        margin : 10,
        nav    : false,
        dots   : false,
        responsive  :{ // I want to determine the number of slider elements according to the range of .right
            0:{
                items:1
            },
            350:{
                items:2
            },        
            600:{
                items:5
            },
        }
    }); 

});

Solution

  • Use responsiveBaseElement

     $("#owl-example").owlCarousel({
          loop   : false,
          margin : 10,
          nav    : false,
          dots   : false,
          responsiveBaseElement:$(".right")[0],
          responsive  :{ // I want to determine the number of slider elements according to the range of .right
            0:{
              items:1
            },
            350:{
              items:2
            },        
            600:{
              items:5
            },
          }
        });
    

    Demo: https://jsfiddle.net/lotusgodkk/7xotrg56/2/