简体   繁体   中英

How can I add class to Owl-item on page load?

I am trying to add custom classes "Big, Medium, Medium" to 3 different owl-items. But this only works when it autoplays. It doesn't work when you see it for the first time. How can I run this code on page load also?

 $('#MySlider .owl-carousel').on('translate.owl.carousel', function(e){
    idx = e.item.index;
    $('#MySlider .owl-carousel').find('.owl-item.big').removeClass('big');
    $('#MySlider .owl-carousel').find('.owl-item.medium').removeClass('medium');
    $('#MySlider .owl-carousel').find('.owl-item').eq(idx).addClass('big');
    $('#MySlider .owl-carousel').find('.owl-item').eq(idx+1).addClass('medium');
    $('#MySlider .owl-carousel').find('.owl-item').eq(idx+2).addClass('medium');
 });

I would like my code to look like this on page load, so that I can style the carousel items. But it only adds the classes after it starts the autoplay.

  <div class="owl-carousel">
      <div class="owl-item big active">...</div>
      <div class="owl-item medium active">...</div>
      <div class="owl-item medium active">...</div>
      <div class="owl-item">...</div>
      <div class="owl-item">...</div>
  </div>

You can use onInitialized callback. This is called when the plugin has been initialized.

$(".owl-carousel").owlCarousel({
  items: 1,
  loop: true,
  dots: false,
  onInitialized: function(event) {
    let element = jQuery(event.target);
    let idx = event.item.index;
    element.find('.owl-item.big').removeClass('big');
    element.find('.owl-item.medium').removeClass('medium');
    element.find('.owl-item').eq(idx).addClass('big');
    element.find('.owl-item').eq(idx + 1).addClass('medium');
    element.find('.owl-item').eq(idx + 2).addClass('medium');
  },
  navContainer: '#nav',
});

Or you can use the event:

 $('#MySlider .owl-carousel').on('initialized.owl.carousel', function(event) {
    let element = jQuery(event.target);
    let idx = event.item.index;
    element.find('.owl-item.big').removeClass('big');
    element.find('.owl-item.medium').removeClass('medium');
    element.find('.owl-item').eq(idx).addClass('big');
    element.find('.owl-item').eq(idx + 1).addClass('medium');
    element.find('.owl-item').eq(idx + 2).addClass('medium');
  }
);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM