babusi babusi - 10 days ago 6
Javascript Question

jQuery perform function when element class changes

I've set up a swiper slider and would like to set off a function when it gets to a specific slide. This is what I've done so far but it isn't working:

// event listener
function addClassNameListener(elemId, callback) {
var elem = $(".swiper-home .swiper-slide:nth-child(2)");
var activeClassName = 'swiper-slide-active';
window.setInterval( function() {
var className = elem.className;
if (className == activeClassName) {
callback();
}
},10);
}

addClassNameListener("foo", function(){
$('.swiper-slide-active .count').each(function () {
//$('body').scrollTop($(this).parent.offset().top);
$(this).prop('Counter', 0).animate({
Counter: $(this).data().total
}, {
duration: $(this).data().seconds * 1000,
easing: 'swing',
step: function (now) {
$(this).text(Math.ceil(now));
}
});
});
alert("changed");

});


I've set up a jsFiddle

Answer

There are actually several things you are doing wrong.

You are accessing className on a elem while it is a jquery object, not a dom element, so it doesn't have this property. Even if it would, it would give all classes separated with spaces, so you should better check elem.hasClass(activeClassName)

Even with that, your callback function will be executed every 10 milliseconds no matter slide was changed or not

If you look at the api of the swiper library you are using, you can use what's provided by them.

E.g. take active slide on slide changed event:

var swiper = new Swiper('.swiper-container', {
    onSlideChangeEnd: function(swiper) {
        var $activeSlide = $(swiper.slides[swiper.activeIndex]);
        //check if this slide is the one you are looking for
        if ($activeSlide.attr('id') == elemId)
        {
            //do your stuff with the active slide
        }
   }
});