How to temporarily change CSS color for 5 seconds using JavaScript and incorporate an easing effect?

Regarding this query:

JavaScript - Modifying CSS color for 5 seconds

Here is a live example of the solution:

http://jsfiddle.net/maniator/dG2ks/

I am interested in adding an easing effect to the transition, gradually making the color fully opaque and then completely transparent.

Answer №1

JavaScript Code Snippet

function generateRGBString(data) {
    if (data.alpha == null) return "rgb(" + data.red + "," + data.green + "," + data.blue + ")";
    else return "rgba(" + data.red + "," + data.green + "," + data.blue + "," + data.alpha + ")";
}


window["highlight"] = function(element, color) {
    var highlightColor = color || {
        "red": 255,
        "green": 0,
        "blue": 0
    };


    var originalBgColor = element.style.backgroundColor;
    var currentAlpha = 1;
    element.style.backgroundColor = generateRGBString(highlightColor);
    setTimeout(function() {
        currentAlpha -= 0.1;
        var newColor = highlightColor;
        newColor.alpha = currentAlpha;
        element.style.backgroundColor = generateRGBString(newColor);

        if (currentAlpha <= 0) {
            element.style.backgroundColor = originalBgColor;
        }
        else {

            setTimeout(arguments.callee, 100);
        }
    });
}

Check it out on jsFiddle: http://jsfiddle.net/dG2ks/32/

Usage Examples

Answer №2

To achieve the desired effect, consider adding the jquery library along with jquery ui, and utilizing the switchClass function.

For detailed instructions, refer to: http://jqueryui.com/demos/switchClass/

You can accomplish this in just 5 lines of code:

Incorporate jquery and jquery ui into the head section of your webpage (2 lines of code). These are externally hosted files that can be easily copied and pasted:

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js" type="text/javascript"></script>
<script src="http://code.jquery.com/ui/1.8.18/jquery-ui.min.js" type="text/javascript"></script>

Subsequently, at the bottom of the body section, include a script containing the following three lines:

$(".yourbutton").click(function() {
        switchClass('.currentclass','.redclass',500) 
        // transition from .currentclass to .redclass in 500 milliseconds
});

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

Resolver for nested TypeORM Apollo queries

I've set up a schema that includes database tables and entity classes as shown below: type User { id: Int! phoneNumber: String! } type Event { id: Int! host: User } Now, I'm attempting to create a query using Apollo like this ...

The jQuery element selection feature is not functioning

Within my HTML file, there lies a table with an empty tbody that is dynamically filled by jQuery once the document is fully loaded. The content of the table body is generated using a PHP script, where jQuery fetches the data via a simple GET request. Belo ...

Convert a prop into a data attribute using Vue.js 2

I have a basic component being displayed as <House :_people="[{'name': 'Kevin'}, {'name':'Bert'}, {'name': 'Timmy'}]"></House> The structure of the component is like this: <templ ...

Upon refreshing the page, next.js 13's useSession() function fails to fetch session information

Currently, I am working on replicating an ecommerce site using nextjs 13. On the order page, I am utilizing useSession from next-auth/react to check if a user is signed in or not. Everything works fine when I navigate to the page through a link, but if I r ...

What is the best way to upgrade Angular from version 10 to 12?

Currently tackling an Angular project migration from version 10 to version 12. Unfortunately, the project seems to be encountering issues post-migration and is not running as expected. ...

Repeatedly iterates through the JSON properties that have been grouped together

https://jsfiddle.net/MauroBros/f1j0qepm/28/#&togetherjs=qedN5gf7SF Upon examining a JSON object, the structure is as follows: var values = [ {"aname":"account1", "pname":"pname1", "vname":"vname1& ...

Executing a Visual Basic subroutine from a jQuery dialog box

Currently, I have a form that includes a jQuery dialog creation. Within this dialog, there is a button generated from an ASP server control that should trigger a function in the code behind when clicked. However, I am encountering an issue where the functi ...

Saving Information to a Specific Location on the Client Side in a CSV File

I am currently working on a static application that uses Angular JS technology. My goal is to write data into a CSV file at a specific path in order for another API to read the data from that location. Despite searching extensively on the internet, I hav ...

The animation in my SVG comes to a halt at a certain point

I am having an issue with my SVG element (shown below) where it stops animating after a certain period of time. I want the animation to continue indefinitely like in this jsfiddle. .path { stroke-dasharray: 20; animation: dash 10s linear; } @ ...

Use the button to trigger the opening of the datepicker in React material UI

Currently, I am incorporating a Datepicker in my project using React Material UI. <TextField id="datetime-local" label="Next appointment" type="datetime-local" defaultValue="2017-05-24T ...

Adjustable table region in PHP

I need help with displaying multiple results in a dynamically created table within my program. Even though I want to show around 25 records, the program cuts off after the 5th record, leaving empty space. The issue seems to be that the area does not expand ...

css how to style a table row with a specific identifier

Although this question has been asked millions of times on the internet, my English skills are not great and I struggle to find the right words to search. I have a table with a specific ID set up like this: <table class="tableClass"> <tr id="one ...

What is the process for generating an HTML document from start to finish with the 'html-element' node module?

Here is an example that demonstrates a flawed method: const HTML = require('html-element'); const doc = `<body> </body>`; const page = HTML.document.createElement(doc) page.appendChild('<div>1</div>') page.append ...

Clickable link remains functional after being hidden

Even though I have hidden the Games-div using the .hide() function in jQuery, my links are still clickable. Is there a way to make them unclickable after being hidden? Here is the link to my code on jsFiddle: http://jsfiddle.net/hypertje/Frv8G/ Note: The ...

Unable to smoothly expand Div in React using Tailwind

I'm facing a challenge in animating a div that contains input elements. I want it to expand smoothly - initially, the text area is small and the other two inputs and buttons are hidden. When clicking on the text area, the input and button should be re ...

Developing and integrating views within a node-webkit desktop application

For my file copier desktop application built with node webkit, I aim to create a seamless flow where the initial check for existing profile data determines the first page displayed. The header with static links/buttons to various views remains consistent ...

Employing a lexicon of hexadecimal color code values to harmonize CSS styles

I have a unique requirement where I need to utilize a dictionary of HTML color codes and then apply those colors as styles. It's an interesting challenge! Here is an example of how my color dictionary looks like: const colorCodes = { red: ...

What methods can I use to make sure the right side of my React form is properly aligned for a polished appearance?

Trying to create a React component with multiple input field tables, the challenge is aligning the right side of the table correctly. The issue lies in inconsistent alignment of content within the cells leading to disruption in overall layout. Experimente ...

Animating a div's width with CSS from left to right

My goal is to create an animation effect for two overlapping divs that will reveal or hide the text inside them. I want one div to animate from left to right while the other animates from right to left, creating a wiping effect where as one piece of text d ...

Retrieving data via AJAX from an SD card

I am using the Atmel SAM4E-EK microcontroller as a server to host a webpage and send data over HTTP protocol. I am currently facing an issue with the download function while trying to download a file from my sd_card, which will not be larger than 512MB. s ...