Reputation:
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
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
Reputation: 10349
$('.item').on('click', '.add-class', function () {
$(this).parents('.box').addClass('active');
setTimeout(function () {
runInit();
}, 1);
});
Upvotes: 1