user2593040
user2593040

Reputation: 199

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>

Upvotes: 2

Views: 1376

Answers (1)

Kalimah
Kalimah

Reputation: 11447

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');
  }
);

Upvotes: 2

Related Questions