user381800
user381800

Reputation:

How to provide a callback for a click function?

I have this code where I need to do something with it after a class is added to it but the function sometimes run before the class is added causing issues. I am trying to provide a callback AFTER the class is added, then run function. I want to do this without using setTimeout if possible.

Here is a snippet of code:

$( '.item' ).on( 'click', '.add-class', function() {
     $( this ).parents( '.box' ).addClass( 'active' );

     runInit(); // sometimes run before above class is added
} );

Upvotes: 0

Views: 49

Answers (2)

vee
vee

Reputation: 38645

You can either check for hasClass (http://api.jquery.com/hasClass/) in your runInit() function definition or trigger a new event after a class gets added like following:

$( '.item' ).on( 'click', '.add-class', function() {
     $( this ).parents( '.box' ).addClass( 'active' ).trigger('boxClassChanged');

     runInit(); // sometimes run before above class is added
} );

// Use your selector here in place of '.box'
$('.box').on('boxClassChanged', function() {
    runInit();
});

This second option is probably what you are looking for.

Upvotes: 1

pdoherty926
pdoherty926

Reputation: 10349

$('.item').on('click', '.add-class', function () {
    $(this).parents('.box').addClass('active');
    setTimeout(function () {
        runInit();
    }, 1);
});

Upvotes: 1

Related Questions