What is the best method for incorporating addClass, delay, and removeClass into your work?

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.

Answer №1

If you wish to implement a delay using .delay(), you must utilize .queue() to specify the queue of functions that will be executed on the element after the delay.

Your code should appear as follows:

$('a').on('click', function() {
  $(this).find('span.code').addClass('bg-success').delay(800).queue(function() {
    $(this).removeClass('bg-success');
    $(this).dequeue();
  });
});

Here is a DEMO snippet showcasing this:

$('a').on('click', function() {
  $(this).addClass('bg-success').delay(800).queue(function() {
    $(this).removeClass('bg-success');
    $(this).dequeue();
  });
});
a {
  width: 100px;
  height: 100px;
  background-color: blue;
  cursor: pointer;
}
.bg-success {
  background-color: red;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<a>A link</a>

Alternatively, you can achieve a similar effect using setTimeout():

$('a').on('click', function() {
  var myLink = $(this).find('span.code');
  myLink.addClass('bg-success');

  setTimeout(function() {
    myLink.removeClass('bg-success');
  }, 800);
});

Limitations of delay():

For more insight into why delay() is recommended for effects only, refer to the jQuery documentation, which outlines the limitations compared to the native JavaScript setTimeout function:

The .delay() method is ideal for delaying between queued jQuery effects. However, it has restrictions such as lacking a way to cancel the delay—.delay() should not replace JavaScript's native setTimeout function in certain scenarios.

Answer №2

According to the provided documentation:

The .delay() method is primarily used for delaying between queued jQuery effects. However, it does have limitations such as lacking the ability to cancel the delay. Therefore, it is not intended to be a replacement for JavaScript's native setTimeout function, which may be more suitable for specific scenarios.

(https://api.jquery.com/delay/)

I recommend utilizing setTimeout in the following manner:

$('a').on('click', function() {
  var span = $(this).find('span.code');
  span.addClass('bg-success');

  setTimeout(function() {
    span.removeClass('bg-success');
  }, 800);
});

Answer №3

If you want to introduce a delay before performing another action, consider using vanilla JavaScript along with the setTimeout() method:

$('a').on('click', function() {
    var myCode = $(this).find('span.code').addClass('bg-success');
    setTimeout(function(){
       myCode.removeClass('bg-success');
    }, 800);
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Error encountered while retrieving data from an array of objects due to hydration issue

In my Nextjs project, I have a sidebar where I am trying to display 5 random posts from an array of objects. The function I defined is working correctly and showing the 5 posts, but I am encountering a Hydration error stating that the Prop alt does not m ...

Is there a way for me to generate a button that directs users to a variety of pages?

How can I create a button that takes me to a random page on my basic website when clicked? I'm having trouble changing the "href" attribute so that it links to a specific page. This is the JavaScript code I've come up with: document.addEventList ...

Getting the highest occurrence of a repeated value within an array using JavaScript (with the help of jQuery)

Dealing with multiple arrays is my current task. I am looking to extract the most duplicated value from each array. In the array [3, 7, 7, 7], the value 7 needs to be found. Each array has a size of 4 elements. Currently, I do not need to consider cases w ...

Tips for including a variable in formData and the steps for implementing it in an ajax procedure

<input type='file' name='inpfile' id='inpfile' accept='image/*' hidden> javascript code var clicked; $('#btnplusa').click(function(){ clicked = 'a'; $('#inpfile').click ...

Displaying data table details through a modal window

After coming across this specific example online, I attempted to implement it myself. Unfortunately, the modal feature does not seem to be functioning as expected. Interestingly, when testing it on jsfiddle, everything works perfectly. Further investigati ...

I'm trying to implement a command in my bot that displays the number of Discord members, but I keep encountering an error

I've encountered an issue with the discord.js v13 member count command. Despite seeking help in various Discord servers, I haven't received any assistance. If anyone could offer their expertise, it would be greatly appreciated. const Discord = re ...

Utilizing GSAP for crafting a dynamic horizontal scrolling section

I am currently working on creating a unique section that transforms into a horizontal scroller once the items (in this case, images) are visible, and then reverts to a vertical scroller once all the items have been scrolled through. My inspiration and ada ...

Steps for invoking the next() function within the beforeRouterEnter guard

I've been grappling with this issue for countless hours now. I'm currently using Vue3 My goal is to implement a beforeRouterEnter guard in order to check the user's role upon login and direct them to the appropriate route accordingly. Once ...

I want to establish the identical response output field name in NestJS by utilizing the @Expose decorator from class-transformer

My Entity definition currently looks like this: export class ItemEntity implements Item { @PrimaryColumn() @IsIn(['product', 'productVariant', 'category']) @IsNotEmpty() itemType: string; @PrimaryColumn() @IsU ...

Executing window.open from Html.Actionlink in ASP.NET MVC 4

Here is the code block I am working with: @foreach (System.Data.DataRow drEquipment in Model.EquipmentList.Rows) { <tr> <td valign="top">@drEquipment["ColumnName"]<br /></td> <td valign="to ...

Tips for aligning a logo in the center of a navigation bar

I'm struggling to center a logo within the navigation bar of a website I am designing. Despite my attempts, I have not been successful in achieving the desired result. My goal is to have the logo positioned in the middle of the navigation bar, with ot ...

Using JavaScript to Align HTML Data to the Right or Left

I have successfully created an HTML table from JSON data and formatted it using JavaScript as required. However, I am facing a challenge with right-aligning all the amounts coming from my JSON data. I want all the numbers to be aligned to the right but I& ...

Using JQuery to Enhance the Highlight Effect: Tips and Tricks

Exploring the functionality of the "highlight" JQuery effect: http://docs.jquery.com/UI/Effects/Highlight You have the ability to modify the background color of any DIV element with a fade in/out effect. However, the provided example demonstrates trigge ...

Showing content based on the current date using Javascript

Although I may not be proficient in Javascript, I was able to gather examples and piece together the following code: var date = new Date().getDate(); var greeting; if (date < 24) { greeting = "Nej det är:"; } else { ...

Issues with embedding iframes

I have a webpage with an embedded iframe that is making ajax requests. However, when I click on a link, it opens in the iframe instead of the main window. I tried using this JavaScript code: window.parent.location.href = url of link but it didn't wo ...

"Troubleshooting issues with $.ajax not functioning correctly after being invoked with

I am facing an issue with my code. It works perfectly fine when I call AA.sendRequest() from the console, but encounters an error when I call it from an onclick event: <a href="/b/Technology" onclick="AA.sendRequest()">Technology</a> Somehow, ...

JavaScript unable to dynamically change CSS styles

I've been struggling to get the color updates working for a while now. My suspicion is that my string return may be invalid, causing the issue. I'm aiming to convert hours, minutes, and seconds into hexadecimal values, but it seems to be failing ...

Unable to retrieve the .attr() from a button that was created using handlebars

I am currently working on developing a web scraper as part of a homework task that involves using Express, Mongoose, Cheerio/axios, and Handlebars. In my "/" route, I retrieve the Mongoose objects and use Handlebars to display them on the page in individua ...

Determine the clicked <a> tag using the onclick handler

There are 5 anchor tags present on my webpage. When one of these tags is clicked, I need to trigger a JavaScript function that will help me identify which specific anchor was clicked. What would be the best way to achieve this? I am looking for solution ...

Tips for Deactivating a Multi-Select Dropdown Upon Page Load and Reactivating it According to Another Dropdown's Value

There are two MultiSelect dropdowns on this page. The functionality I am looking for is as follows: Upon loading the page, I want the multiselect02 field to be disabled. Only when I choose the option "Item2" from multiselect01, do I want the multiselect ...