Learn how to dynamically apply a CSS attribute for a set period of time using jQuery and automatically revert it back to its original state after 2 seconds

Is there a way to apply a CSS attribute to a specific element (like a div) for only 2 seconds? Here is what I have tried so far:

HTML:

<div class="custom-div">bar</div>
<input class="button" type="button" value="press me" />

JQuery:

$(".button").click(function(e) {
   $(".custom-div").css({"background-color": "lightblue"});
});

The issue with the code above is that it will maintain the changes indefinitely. Is there a way to restrict this change to a specific time frame?

Answer №1

For the optimal solution, I believe using a CSS class is the way to go, especially if the previous border style or other applied CSS rules are unknown:

CSS

.borderStyle{
    border: 1px solid #ccc!important;
}

JavaScript

$('.btn').click(function(){
    $('.div').addClass("borderStyle");
    setTimeout(function(){ $('.div').removeClass("borderStyle"); }, 2000);
});

Toggle Class Version

$('.btn').click(function(){
    $('.div').toggleClass("borderStyle");
    setTimeout(function(){ $('.div').toggleClass("borderStyle"); }, 2000);
});

Here is a link to the fiddle.

If the toggleClass method is not working for you, I recommend keeping it included in my answer for future reference.

Answer №2

Here is a suggestion for achieving the desired effect:

$(".btn").on("click", function(e) {
    $(".box").css({"border": "1px solid #ccc"});
    setTimeout(function(){
        $(".box").css({/* Your initial css styles */});
    }, 2000);
});

Answer №3

To achieve this effect, simply incorporate a setTimeout() function that will execute after 2 seconds and remove the border.

$(".btn").on("click", function() {
    $('.foo').css('border', '1px solid #ccc');
    setTimeout( function() { 
        $('.foo').css('border', 'none');
    }, 2000);
});

View Working Example on JSFIDDLE

In this code snippet, I replaced your use of .click() with .on(). You can learn more about why it's advantageous to use .on() over .click() here, and find guidance on how to implement it here.

Answer №4

Following a delay of two seconds, the CSS attributes will be removed:

$(".btn").click(function(e) {
   $(".div").css({"border": "1px solid #ccc"});
   setTimeout(function() { 
       $(".div").css({
           'border' : 'none',
           'width' : '30px',
           'top' : '10px',
           'left' : '30px',
           'bottom' : '10px',
           'right' : '30px'
       });
   }, 2000);
});

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

What is the CSS code to apply a color to a white area on a

How do I add color to the white space between the blue blocks? Here is the code snippet: #nav{ padding:0; } .rech{ margin-left: 785px; } .px{ margin-left: 3px; } #nav li{ display:inline; } #nav li a, .rech{ font-family:Arial; font- ...

Customize the appearance of polygons in OpenLayers 2 by adjusting the fill color and opacity

I am aiming to use different fill colors and opacity values for various shapes (such as Triangle, Circle, Square, Hexagon, etc.). Although I can draw the shapes, set different titles, and stroke colors with the code below, I'm struggling to define th ...

Incorrect placement of navigation in HTML/CSS dimensions

I'm working on my new portfolio and I've run into an issue with the navigation placement that I can't seem to solve. The text should be aligned with the lines on the sides, but instead it's shifted right and down. I'm struggling t ...

Click on the spliced image to alter the table

Seeking assistance with jquery as a beginner. I have three tables containing spliced images, each with its own id. When an image in one table is clicked, I want the entire table to switch to another one with a different id. Struggling to figure out how to ...

Retrieve the highest date value from a collection of objects

Within a React.js component, I have the following array: const data = [{ date: '2017-12-21T07:43:00Z', value: 7000 }, { date: '2017-12-21T09:41:00Z', value: 1500, }, { date: '2017-12-23T10:59:00Z', value: 2000 }] ...

Utilize the precise Kendo chart library files rather than relying on the kendo.all.min.js file

My application currently uses the Kendo chart, and for this purpose, it utilizes the "kendo.all.min.js" file which is quite large at 2.5 MB. To optimize the speed performance of the application, I decided to only include specific Kendo chart libraries. In ...

Improving the Performance of HTML/CSS Animations - Enhanced Animation Speed

I have created an HTML page with CSS animation and transitions. <div class="container-fluid" id="team"> <div class="row first"> <div class="wrapper"></div> </div> <div class="row second"> <div class="wrapper" ...

The time zones between Node 8 and Node 11 are not the same

Executing a basic new Date().toString() command produces different results on Node 11 compared to Node 8. In Node 11, the output includes the full timezone abbreviation like this: 'Fri May 10 2019 10:44:44 GMT-0700 (Pacific Daylight Time)' On t ...

Delete the final character from the value stored in the map

After retrieving data from the backend, I receive: {"Item":{"userEmail":"b","Username":"bUsername","Push":"sdsdsd","Password":"sdsds","Buddy":{"datatype":"SS","contents":{"Drake":"Drake","Ola":"Ola","b":"b","d":"d"}}}} Utilizing Object.Keys, I filter ...

Monochrome tabletop solid in one hue

I'm trying to eliminate the space between the columns in my table so it looks solid. Here's the CSS style I've been using: <style> tr, th, td {margin:0;padding:0;border:0;outline:0;font-size:90%;background:transparent;} table{ margin: ...

The alignment of elements on the right and left sides is not functioning as intended

I've been facing an issue with the alignment of my floats on my brand new website www.unicmedia.nl/case/oranje. Surprisingly, they seem to work fine in IE this time, but Firefox and Chrome are completely out of sync. Despite trying numerous solutions ...

Best Practices for Integrating PHP Code into an HTML File for Contact Form Placement

My current setup involves an html file named index.html, which contains the code for my contact form fields such as name and email. Is there a way to include PHP code in this file without converting it to index.php? ...

When I click on my navbar toggle button, why isn't my text displaying?

I'm experiencing an issue with my navbar toggle. The toggle button works fine, but when I click on it, the text inside the button doesn't show up. I've checked the Bootstrap docs to make sure I didn't miss any steps, but I can't se ...

Unable to retrieve information from server

enter image description here <!DOCTYPE html> <html ng-app="myApp"> <head> <title>ContactApp</title> <!-- Latest compiled and minified CSS --> <link rel="stylesheet" href="https://maxcdn.bootst ...

Export default does not actually yield a function; rather, it returns an object

I recently developed a function that is responsible for importing a script from a specified source, calling its exported function, and handling the returned result. To simplify things, I have streamlined the code to focus solely on returning the result. co ...

CSS Flexibility

Greetings everyone, it's been a while since I dabbled in web development. I recently worked on my site with the intention of making it responsive using flexbox. This is my first time posting here, so please guide me on how to seek help more effective ...

Tips for adding additional columns to the final data output

When retrieving data from the database and binding it to a table, I found that I wanted to include additional columns in the displayed data. While I am getting the name value from the database, I also want to add a city column to the table on the UI. View ...

Having trouble sending the welcome message?

Upon someone's entry, an error message Cannot read properties of undefined (reading 'send') is popping up in the console. I have ensured that all the necessary intents are selected for a proper welcome system or message display. Even when I ...

Achieving the extraction of a particular string from an HTML element using JavaScript

<input id="WD01B3" ct="CB" lsdata="{2:'WD01B4',4:'Any',20:'\x7b\x22WDA_TYPE\x22\x3a\x22DROPDOWN_BY_KEY\x22,\x22WDA_ID\x22\x3a\x22ABCA950297D2C0C432BAB9BB ...

Unlock the potential of AngularJS services with this innovative design strategy

I am currently developing an AngularJS client application that will communicate with a REST server. To handle the interaction between the client and server, I have decided to use the $resource abstraction from AngularJS. Each resource is being written as ...