Search code examples
jquerycycle

trigger an alert after slide change with malsup Cycle


I'm using Malsup's jQuery Cycle plugin and have the following code that runs it nicely and also adds the class .current to the slide that is active.

$('#banner') 
    .cycle({ 
    fx: 'fade', 
    speed: '1000', 
    timeout: '8000', 
    pager: '#pager',
    next: '#next',
    prev: '#prev',
    cleartypeNoBg: 'true',
    before: function(){
       $(this).parent().find('.current').removeClass();
    },
    after: function(){
       $(this).addClass('current');
    }
});

Now what i wanted to do (for the sake of testing codes) is trigger an alert when the .current class changes slide. I have tried:

$('#banner').find('.current').change(function(){
    alert('hello');
});

But it didnt work at all, what is it that i'm doing wrong?


Solution

  • .change() only works on inputs or contenteditable. There is no event triggered when the class changes. You have to create your own.

    $('#banner') 
        .cycle({ 
        fx: 'fade', 
        speed: '1000', 
        timeout: '8000', 
        pager: '#pager',
        next: '#next',
        prev: '#prev',
        cleartypeNoBg: 'true',
        before: function(){
           $(this).parent().find('.current').removeClass();
        },
        after: function(){
           $(this).addClass('current').trigger('changeClass');
        }
    });
    

    And then you do

    $('#banner').on('changeClass', function(){
       alert($(this).find('.current').index());
    })