Using jQuery, you can apply a class to an element and then have it removed automatically after

Is there a way to add a class and then remove it after 500 milliseconds using jQuery? I tried using delay() but it didn't work as expected. Here is a simple example where I am changing the background color:

Check out this code pen

jQuery

$('.box').click(function(){

 $('.box').addClass("bg1").delay(500).removeClass("bg1");
});

Answer №1

If you want to achieve this effect, consider using a timeout.

For example: jsfiddle

$('.box').on('click', function(){

    var element = $(this);

    element.addClass("bg1");

    setTimeout(function(){
        element.removeClass("bg1");
    }, 500);

});

Answer №2

Make sure to incorporate a timeout function or if you are using delay, ensure it is placed in the queue:

Check out the DEMO

$('.box').click(function () {
    $('.box').addClass("bg1").dequeue().delay(500).queue(function () {
        $(this).removeClass("bg1");
    });
});

Answer №3

Using the Timeout Function in jquery can provide you with improved results.

For example:

$('.box').click(function(){
        $('.box').addClass("bg1");
        setTimeout(function(){
            $('.box').removeClass("bg1");
        },500);
    });

Answer №4

Utilize:

setTimeout(function() {
    // Perform actions
}, 500);

Answer №5

$('#container').on('click', '.box', function(){
 $('.box').addClass("highlight");
 setTimeout(function() {
    $('.box').removeClass("highlight")
 }, 500);
});

This is one way to achieve the desired effect

Answer №6

Check out this solution:

$('.square').click(function(){
    $('.square').addClass("highlight");
    setTimeout("$('.square').removeClass('highlight')", 500);
});

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

Utilizing Ajax to Dynamically Update Link Styles

When using an AJAX request to load a portion of a webpage, the content is delivered by a framework and then inserted into the DOM tree using jQuery. Everything seems to be working well so far. However, I encountered an issue when trying to use background ...

Applying CSS selectors to target child elements within a select option

I am looking to apply a CSS selector only on select option child values. I have assigned an id to the selector and now I want to apply different CSS styles to each child (child 1, child 2, etc). <select name="options[81]" id="select_81" class="required ...

Problem with Chrome Compatibility for Bootstrap Carousel

My webpage features a carousel implemented as a slider. It seems to be working fine in Firefox and mobile browsers, except for Chrome where it doesn't show up at all. I can't seem to figure out what's causing the issue. Here is the syntax I& ...

Whenever I create the code using javascript, padding seems to always show up

I have a basic stacked row layout that displays an upper box and lower box without any padding. <span id="route" class="small"> <div class="row" style="border-style:solid;"> <div class="col-md-12 col-12"> <p>UpperBox</p& ...

utilizing geographical coordinates in a separate function

I have a program that enables users to access the locations of communication cabinets. I am attempting to utilize html5 to transmit latitude and longitude information to a php script (geo.php) in order to update the database record with map coordinates. Ho ...

Utilizing a mySQL database to insert HTML content into a div: a step-by-step guide

Presently, this jQuery snippet is being utilized to insert HTML content from another file into a div: $("#list li a").click(function(){ var id = this.id; $('#content').fadeOut('fast', function(){ $.ajax({url:"./html/" + id + ".html ...

Unable to see media queries on desktop by default, but can easily view them by inspecting the page

As I delved into a tutorial on media queries, I encountered a perplexing issue. Upon opening the HTML file in Chrome or Firefox, all I saw was a blank page with no content displayed. However, upon inspecting the page, the code appeared as expected and I co ...

Changing the color of a div element dynamically with JavaScript

Is there a way to improve the code below so that the background color of this div box changes instantly when clicked, without needing to click twice? function updateBackgroundColor(platz_id) { if(document.getElementById(platz_id).style.backgroundCol ...

Dealing with client-side session expiration

I am looking to implement a solution for handling session timeouts on the client side. At present, our asp.net MVC code does not address session timeouts. Is there a workaround I can employ to display an alert box when the session expires during ajax reque ...

"Learn how to create a scrolling div using a combination of CSS and JavaScript with absolute and relative

After relying solely on "pre-made" components like Mui or TailWind, I decided to create a component using only CSS and maybe JavaScript. However, I encountered some difficulties when attempting to position a div inside an image using relative and absolute ...

The header, main content, and footer sections expand to occupy the entire page

I am in need of HTML structure that looks like the following: <header></header> <div id='main'></div> <footer></footer> I want all elements to be positioned relatively. The header and footer will have fixed h ...

Concealing certain elements within a loop using a "show more" button

In my PHP code, I am utilizing a foreach loop in the following manner: <div class="items"> @foreach($results as $details) <div class="col s2 l2"> {{ $details }} </div></div> My approach involves using the blade templating feature ...

Utilize AJAX to accurately capture and handle error codes

Here is a snippet of code that I want to send to my server: $.ajax({ type: 'POST', url: 'post.php', data: { token: '123456', title: 'some title', url: 'http://somedomain.com', data: & ...

What is the best way to dynamically pass JSON object values to PHP?

Greetings, I am new to JSON and Ajax. Although my question may seem trivial, I believe that even the simplest inquiries are crucial in the learning process. My dilemma involves passing two parameters (giorno and periodo) via Ajax: For example: 'gior ...

Is there a way to insert the Ajax value into a PHP string in this particular scenario?

Is there a way to store the ajax result directly into a php string without using .html(), .text(), or .val() in the ajax success function? jQuery.ajax({ url:'member_search.php', type:'POST', data:{ search_text: $(".res ...

Making the black background stretch to the full height and allowing for scrolling when necessary

Check out this webpage where the text in the box extends beyond the page when scrolling, revealing the full content while the black background expands correctly. Visit this page to see that the text in the box is small, but I want the black background t ...

Top Method for Incorporating Syntax Highlighting into Code Blocks - React Sanity Blog

I'm currently exploring the most effective method to incorporate syntax highlighting into my react sanity.io blog. Here's a look at the article component I've developed using react: import React, {useEffect, useState} from "react"; import ...

Transferring information to a MySQL database via an AJAX POST operation

I'm trying to use AJAX to send a user-typed string and add it to a database: New manufacturer: <input type="text" id="new_mfg" size="20"> <button id="add_mfg">Add</button> <script> $("#add_mfg").click(function(e){ ...

Obtain the value of "data-something" attribute from an <option> element within a <select> element

Can anyone help me with this HTML snippet? <select id="something"> <option value="1" data-something="true">Something True</option> <option value="2" data-something-else="false">Something Else False</option> </selec ...

Divide Panel Content Enclosed by a CSS Figure

Need assistance with creating a diamond shape in CSS with two sets of text on each side of a separating line inside the diamond. I've tried aligning and floating the text without luck. Any help would be appreciated. body { background-color: pink; } ...