最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Reload Owl Carousel 2 when side navigation opens or closes - Stack Overflow

programmeradmin0浏览0评论

I am working on a website, and it is built off a theme. In the body of the site is structured to have a left-panel div which houses the navigation and a right-panel div which houses the body content.

When the left-panel opens from a collapsed view (showing only icons) to the full view (showing the nav text), owl-carousel, since it's loaded on page load, doesn't readjust the width.

I've tried a few methods to try and reload the carousel, following their API, but am not successful. The body doesn't have a set width, such as inline styles, but instead the class left-menu-open is set, when the left menu is open.

I've also looked at several other cases of people trying to do the same thing, but none of their code examples work.

Below is my code. I am running this in a .php file, so I am able to load multiple sliders in the body content, without them rotating in relation. The carousel loads and functions fine, it's just that it begins to clip if the page is loaded with the nav open and one closes the nav, or the 3rd slide shows if the page is loaded with the nav closed and is opened.

One method I've tried is

if ( $( 'body' ).resize() { }

if ( $( 'body' ).hasClass( 'left-nav-open' ) { } else if ( !$( 'body ').resize() { }

(function($) {
  $(function() {
    var $owl = $('.owl-<?php echo $owl_widget_title; ?>');

    $owl.owlCarousel({
      // your initial option here, again.
      loop:true,
      nav:true,
      navText: ["<i class=\"fa fa-chevron-left\"></i>","<i class=\"fa fa-chevron-right\"></i>"],
      dots: false,
      lazyLoad: true,
      lazyContent: true,
      autoplaySpeed: 1000,
      autoplayTimeout: 7000,
      autoplayHoverPause: true,
      responsive : {
        0 : {
          items: 1,
          slideBy: 1,
          autoHeight:true,
        },
        992 : {
          items: <?php echo $num_of_items; ?>,
          slideBy: <?php echo $num_of_items; ?>,
        }
      }
    });

  });

})(jQuery)

I've tried destroy.owl.carousel, and then initialize.owl.carousel but neither of those seem to work or run at all.

Any and all help is appreciated! Thank you

I am working on a website, and it is built off a theme. In the body of the site is structured to have a left-panel div which houses the navigation and a right-panel div which houses the body content.

When the left-panel opens from a collapsed view (showing only icons) to the full view (showing the nav text), owl-carousel, since it's loaded on page load, doesn't readjust the width.

I've tried a few methods to try and reload the carousel, following their API, but am not successful. The body doesn't have a set width, such as inline styles, but instead the class left-menu-open is set, when the left menu is open.

I've also looked at several other cases of people trying to do the same thing, but none of their code examples work.

Below is my code. I am running this in a .php file, so I am able to load multiple sliders in the body content, without them rotating in relation. The carousel loads and functions fine, it's just that it begins to clip if the page is loaded with the nav open and one closes the nav, or the 3rd slide shows if the page is loaded with the nav closed and is opened.

One method I've tried is

if ( $( 'body' ).resize() { }

if ( $( 'body' ).hasClass( 'left-nav-open' ) { } else if ( !$( 'body ').resize() { }

(function($) {
  $(function() {
    var $owl = $('.owl-<?php echo $owl_widget_title; ?>');

    $owl.owlCarousel({
      // your initial option here, again.
      loop:true,
      nav:true,
      navText: ["<i class=\"fa fa-chevron-left\"></i>","<i class=\"fa fa-chevron-right\"></i>"],
      dots: false,
      lazyLoad: true,
      lazyContent: true,
      autoplaySpeed: 1000,
      autoplayTimeout: 7000,
      autoplayHoverPause: true,
      responsive : {
        0 : {
          items: 1,
          slideBy: 1,
          autoHeight:true,
        },
        992 : {
          items: <?php echo $num_of_items; ?>,
          slideBy: <?php echo $num_of_items; ?>,
        }
      }
    });

  });

})(jQuery)

I've tried destroy.owl.carousel, and then initialize.owl.carousel but neither of those seem to work or run at all.

Any and all help is appreciated! Thank you

Share Improve this question asked Apr 12, 2017 at 13:43 IshioIshio 7652 gold badges9 silver badges29 bronze badges
Add a ment  | 

4 Answers 4

Reset to default 5

To update owl after resize of container one would need to call .onResize() _handler on its data. The updateOwl() function should look like this:

updateOwl = function(){
  $(".owl-carousel").each(function() {
    $(this).data('owl.carousel').onResize();
  });
};

The only thing to watch for is when exactly to call this function. I assume the sidebar is not jumping into position, but rather smoothly animating. The call to .onResize() needs to be delayed by the duration of animation, so the size of the carousel is calculated based on final content size. Delay the execution of updateOwl() by wrapping it into a setTimeout() (equal or slightly longer than the sidebar animation duration):

$(document).on('click', '.sidebarToggle', function(){
  setTimeout(function(){
    updateOwl();        
  },   321)
});

...where .sidebarToggle would be your sidebar opener.

Working example:

(function($) {
  var $owl = $('.owl-carousel'),
      updateOwl = function(){
        $owl.each(function() {
          $(this).data('owl.carousel').onResize();
        });
      };
  
  $owl.owlCarousel({
    loop: true,
    nav: true,
    navText: ['<i class="fa fa-chevron-left"></i>', '<i class="fa fa-chevron-right"></i>'],
    dots: false,
    lazyLoad: true,
    autoplaySpeed: 1000,
    autoplayTimeout: 7000,
    autoplayHoverPause: true,
    responsive: {
      0: {
        items: 1,
        slideBy: 1,
        autoHeight: true,
      },
      992: {
        items: 3,
        slideBy: 3,
      }
    }
  });
  
  $(document).on('click', '.sidebarToggle', function(){
    $('body').toggleClass('sidebarOpen'); 
    setTimeout(function(){
      updateOwl();        
    }, 321)
  });

  $(window).on('resize', updateOwl); 
  
})(jQuery)
body {
  margin: 0;
  transition: padding-left .3s cubic-bezier(.4,0,.2,1);
  }
.sidebar {
  height: 100vh;
  position: absolute;
  width: 200px;
  background-color: #888;
  left: -200px;
  top:0;
  transition: left .3s cubic-bezier(.4,0,.2,1);
  box-sizing: border-box;
}
.sidebarOpen .sidebar {
  left: 0;
}

body.sidebarOpen {
  padding-left: 200px;
}
.owl-carousel .owl-item {
  padding: 0 45px;
  box-sizing: border-box;
}
.owl-carousel .owl-item > div{
  min-height: 135px;
  width: 100%;
  border: 1px solid #ccc;
  display: flex;
  flex-direction: column;
  justify-content: center;
  align-items: center;
  background-color: Gainsboro;
  border-radius: 3px;
}
button {
  margin: 15px;
}
.owl-carousel {
  position: relative;
  margin: 15px 0 0;
}
.owl-nav >div {
  position: absolute;
  top: 50%;
  width: 20px;
  transform: translate(-50%, -50%);
  text-align: center;
}
.owl-prev {left: 20px}
.owl-next {left: calc(100% - 20px);}
<link href="https://maxcdn.bootstrapcdn./font-awesome/4.7.0/css/font-awesome.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare./ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css" rel="stylesheet"/>
<link href="https://cdnjs.cloudflare./ajax/libs/OwlCarousel2/2.2.1/assets/owl.theme.default.css" rel="stylesheet"/>
<script src="https://ajax.googleapis./ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js"></script>


<div class="sidebar"></div>

<div class="owl-carousel">
  <div> Your Content </div>
  <div> Your Content </div>
  <div> Your Content </div>
  <div> Your Content </div>
  <div> Your Content </div>
  <div> Your Content </div>
  <div> Your Content </div>
</div>
<button class="sidebarToggle">SidebarToggle</button>

If the above is not working for you, I'll need to have a look at your implementation to be able to debug it.

Side note: lazyContent is currently unavailable. According to plugin author:

...lazyContent was introduced during beta tests but i removed it from the final release due to bad implementation. It is a nice options so i will work on it in the nearest feature.

I use destroy.owl.carousel to destroy carousel. Carousel reinitialize on click of left navigation menu

var $owl = $('.owl-carousel');
/*inital on load */
$owl.owlCarousel({
  items: 6,
  lazyLoad: true,
  loop: true,
  margin: 10,
});
/*on click of navigation menu */
function resizeCarosel(obj) {
  if (obj.classList.contains('is-open')) {
    $owl.trigger('destroy.owl.carousel'); /*destroy Carousel*/
    $owl.owlCarousel({ /*reinitialize Carousel*/
      items: 6,
      lazyLoad: true,
      loop: true,
      margin: 10,
    });
  }
  if (obj.classList.contains('is-closed')) {
    $owl.trigger('destroy.owl.carousel'); /*destroy Carousel*/
    $owl.owlCarousel({ /*reinitialize Carousel*/
      items: 2,
      lazyLoad: true,
      loop: true,
      margin: 10,
      /*for responsive 
        items: 4,
        responsiveClass: true,
        responsive: {
          0: {
            items: 1,
            nav: true
          },
          600: {
            items: 3,
            nav: false
          },
          1000: {
            items: 5,
            nav: true,
            loop: false
          }
        }
      */
    });
  }

}
<script type="text/javascript" src="//code.jquery./jquery-1.11.0.js"></script>

<link rel="stylesheet" type="text/css" href="https://maxcdn.bootstrapcdn./bootstrap/3.3.5/css/bootstrap.min.css">
<link rel="stylesheet" type="text/css" href="https://rawgit./FragCoder/bootstrap-left-slide-menu/master/bootstrap-left-slide-menu.css">
<script type="text/javascript" src="https://maxcdn.bootstrapcdn./bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script type="text/javascript" src="https://rawgit./FragCoder/bootstrap-left-slide-menu/master/bootstrap-left-slide-menu.js"></script>
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit./smashingboxes/OwlCarousel2/2.0.0-beta.3/dist/assets/owl.carousel.css">
<link rel="stylesheet" type="text/css" href="https://cdn.rawgit./smashingboxes/OwlCarousel2/2.0.0-beta.3/dist/assets/owl.theme.default.css">
<script type="text/javascript" src="https://cdn.rawgit./smashingboxes/OwlCarousel2/2.0.0-beta.3/dist/owl.carousel.js"></script>

<div id="wrapper" class="">
  <div class="overlay" style="display: none;"></div>
  <nav class="navbar navbar-inverse navbar-fixed-top" id="sidebar-wrapper" role="navigation">
    <ul class="nav sidebar-nav">
      <li class="sidebar-brand">
        <a href="#"> BLESM </a>
      </li>
      <li>
        <a href="#"><i class="glyphicon glyphicon-camera"></i> Photo</a>
      </li>
      <li>
        <a href="#"><i class="glyphicon glyphicon-facetime-video"></i> Video</a>
      </li>
      <li>
        <a href="#"><i class="glyphicon glyphicon-headphones"></i> Music</a>
      </li>
      <li>
        <a href="#"><i class="glyphicon glyphicon-cloud"></i> Cloud</a>
      </li>
      <li>
        <a href="#"><i class="glyphicon glyphicon-th"></i> Apps</a>
      </li>
      <li>
        <a href="#"><i class="glyphicon glyphicon-cog"></i> Settings</a>
      </li>
    </ul>
  </nav>
  <div id="page-content-wrapper">
    <button type="button" class="hamburger animated fadeInLeft is-closed" data-toggle="offcanvas" onclick="resizeCarosel(this)">
      <span class="hamb-top"></span>
      <span class="hamb-middle"></span>
      <span class="hamb-bottom"></span>
    </button>
    <div class="container">
      <div class="owl-carousel owl-theme">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=1" data-src-retina="https://placehold.it/350x250&text=1-retina" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=2" data-src-retina="https://placehold.it/350x250&text=2-retina" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=3" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=4" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=5" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=6" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=7" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=8" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=9" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=10" alt="">
        <img class="owl-lazy" data-src="https://placehold.it/350x250&text=11" alt="">
      </div>

    </div>
  </div>
</div>

You should be able to get the job done by simple deleting the element from the DOM (jquery has a function .remove()) and then recreating exactly as you did with the first one. Notice that you will have to store the variables that e from the server in the client.

  1. I propose to trigger the refresh.owl.carousel event.

  2. My sidebar uses transition so I need to detect the transitionend event.

  3. I've set the .main block as the responsiveBaseElement. Now the carousel adjusts to the width of its container, and not to the width of the entire page.

  4. And I've added a few more jump points to make the responsive changes more visible.

Please check the result. Is it what you want to achieve?

https://codepen.io/glebkema/pen/zwozRx

var $owl = $('#myCarousel');
var owl = $owl.owlCarousel({
  autoplay: true,
  autoplayHoverPause: true,
  dots: false,
  loop: true,
  nav: true,
  navText: [ "<i class=\"fa fa-chevron-left\"></i>",
             "<i class=\"fa fa-chevron-right\"></i>" ],
  responsiveBaseElement: '.main',
  responsive : {
    0 : {
      items: 1,
      slideBy: 1,
    },
    400 : {
      items: 2,
      slideBy: 1,
    },
    768 : {
      items: 3,
      slideBy: 2,
    },
    992 : {
      items: 4,
      slideBy: 2,
    },
    1200 : {
      items: 5,
      slideBy: 2,
    },
  },
});

$('.sidebar-switcher').click(function(){
  $('body').toggleClass( 'body-open' );
  $('.main').one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend", function(event) {
    owl.trigger('refresh.owl.carousel');
  });
});
* { box-sizing: border-box; }
body {
  margin: 0;
}

/** sidebar closed **/
.main,
.sidebar {
  -webkit-transition: margin .4s ease-out;
     -moz-transition: margin .4s ease-out;
      -ms-transition: margin .4s ease-out;
       -o-transition: margin .4s ease-out;
          transition: margin .4s ease-out;
}
.main {
  padding: 0 36px;
  margin-left: 70px;
}
.sidebar {
  background: #ccc;
  float: left;
  height: 100vh;
  margin-left: -230px;
  position: relative;
  width: 300px;
}
.sidebar-switcher {
  position: absolute; top: 12px; right: 12px;
}
.sidebar-switcher:before {
  content: '\f0c9';
  cursor: pointer;
  font-family: 'FontAwesome';
  font-size: 30px;
  line-height: 1;
  position: absolute; top: 12px; right: 12px;
}

/** sidebar opened **/
.body-open .main {
  margin-left: 300px;
}
.body-open .sidebar {
  margin-left: 0;
}
.body-open .sidebar-switcher:before {
  content: '\f00d';
}

/** owl carousel **/
.owl-item > div {
  margin: 12px;
}
.owl-next,
.owl-prev {
  position: absolute;
  top: 0;
  width: 36px;
  bottom: 0; 
}
.owl-next {
  left: 100%;
  margin-left: -12px;
}
.owl-prev {
  right: 100%;
  margin-right: -12px;
}
.owl-next i,
.owl-prev i {
  font-size: 30px;
  line-height: 24px;
  margin-top: -12px;
  position: absolute;
  top: 50%;
}
.owl-next i {
  left: 12px;
}
.owl-prev i {
  right: 12px;
}
.owl-next:hover i,
.owl-prev:hover i {
  color: red;
}
<link rel="stylesheet" href="https://cdnjs.cloudflare./ajax/libs/OwlCarousel2/2.2.1/assets/owl.carousel.min.css">
<link rel="stylesheet" href="//maxcdn.bootstrapcdn./font-awesome/4.7.0/css/font-awesome.min.css">

<div class="sidebar">
  <div class="sidebar-switcher"></div>
</div>
<div class="main">
  <div class="owl-carousel" id="myCarousel">
    <div><img src="https://via.placeholder./400x200/fc3/fff/?text=1" alt=""></div>
    <div><img src="https://via.placeholder./400x200/693/fff/?text=2" alt=""></div>
    <div><img src="https://via.placeholder./400x200/369/fff/?text=3" alt=""></div>
    <div><img src="https://via.placeholder./400x200/f63/fff/?text=4" alt=""></div>
    <div><img src="https://via.placeholder./400x200/936/fff/?text=5" alt=""></div>
  </div>
</div>

<script src="https://ajax.googleapis./ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare./ajax/libs/OwlCarousel2/2.2.1/owl.carousel.min.js"></script>

发布评论

评论列表(0)

  1. 暂无评论