I've been tasked with a simple job - when a link is clicked, I need to add the bg-success
class to its child element, wait 800ms, then remove that class.
Initially, I successfully triggered the addition of the class using addClass()
upon click:
$('a').on('click', function() {
$(this).find('span.code').addClass('bg-success');
});
I was also able to trigger the removal of the class on click:
$('a').on('click', function() {
$(this).find('span.code').removeClass('test-class');
});
Adding a delay and fadeOut after adding the class worked too:
$('a').on('click', function() {
$(this).find('span.code').addClass('bg-success').delay(800).fadeOut(400);
});
However, attempting to add a class, delay, and then remove it did not yield the desired result. Despite trying variations in delay time, the behavior remained unchanged. Interestingly, using two addClass()
calls simultaneously didn't acknowledge the delay either:
$('a').on('click', function() {
$(this).find('span.code').addClass('bg-success').delay(8000).removeClass('bg-success');
});
I scoured Stackoverflow for solutions but to no avail. It seems that the delay()
function functions as expected with fadeIn/fadeOut, yet behaves differently with addClass/removeClass operations.
If anyone has encountered this issue before, your insights would be greatly appreciated. Thank you.
Update:
Please refer to the comments below for the resolution.
On another note, could someone proficient in jQuery shed some light on why this peculiar behavior exists? While the proposed workaround might seem straightforward, understanding the rationale behind jQuery's design choices would help prevent falling into similar traps in the future.
Your expertise is valued in clarifying this matter. Thank you.