javascript - Swiper slider add class to active slide when attribute in HTML is set - Stack Overflow

I want to add class to navbar when active slide has got attribute set for example "navbar-dark&quo

I want to add class to navbar when active slide has got attribute set for example "navbar-dark". I tried with class but my function doesn't work perfect. It is when I changed slide the class was adding to the second slide not to first slide.

$(document).ready(function () {
    var mySwiper = new Swiper('.swiper-container', {
        direction: 'horizontal',
        loop: false,
        mousewheel: {
            invert: false,
        },
    });
    mySwiper.on('slideChange', function (realIndex) {
        if ($('.swiper-slide.swiper-slide-active').hasClass('dark')) {
            $('#navbar').addClass('darknav')
        } else {
            $('#navbar').removeClass('darknav');
        }
    });
});

I want to add class to navbar when active slide has got attribute set for example "navbar-dark". I tried with class but my function doesn't work perfect. It is when I changed slide the class was adding to the second slide not to first slide.

$(document).ready(function () {
    var mySwiper = new Swiper('.swiper-container', {
        direction: 'horizontal',
        loop: false,
        mousewheel: {
            invert: false,
        },
    });
    mySwiper.on('slideChange', function (realIndex) {
        if ($('.swiper-slide.swiper-slide-active').hasClass('dark')) {
            $('#navbar').addClass('darknav')
        } else {
            $('#navbar').removeClass('darknav');
        }
    });
});
Share Improve this question asked Feb 20, 2019 at 17:42 SynysterGates999SynysterGates999 231 gold badge1 silver badge5 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 1

I googled for "swiper jQuery plugin", opened the first suggested page and went to the API. And there's the Events section, and there's the .on init method. Let's try it

jQuery(function($) {

  function darkNav() {
    //if ( $('.swiper-slide.swiper-slide-active').hasClass('dark') ) { // `this` rather?
    if ( $(this).find('.swiper-slide-active').hasClass('dark') ) {
      $('#navbar').addClass('darknav')
    } else {
      $('#navbar').removeClass('darknav');
    }
  }

  var mySwiper = new Swiper('.swiper-container', {
    direction: 'horizontal',
    loop: false,
    mousewheel: {
      invert: false,
    },
    on: {
      init: darkNav,          // do also on init
      slideChange: darkNav    // is this needed?
    }
  });

});

Also, instead of $('.swiper-slide.swiper-slide-active').hasClass('dark') you could rather try with $(this).find('.swiper-slide-active').hasClass('dark')

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744966014a4603683.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信