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

Tips for centering text inside a div using a separator

During my side project, I decided to use the angular material divider but encountered issues with aligning the text correctly. https://i.stack.imgur.com/zg1mu.png The problem can be seen in the image provided - the text on the right side is not aligned b ...

eslint is designed to not handle multiple package.json files

There are two package.json files in my project root folder └ app ---- /public └ /styles └ /src └ package.json └ eslintrc.json └ webpack.config.js └ server - /something └ /something ...

Error occurs despite successful 200 response from Ajax delete request

I've been working on setting up a simple API for my project and encountered an issue. When I send a DELETE request using jQuery Ajax, the request goes through successfully, deletes the specified entry in the database, returns a status of 200, but trig ...

Prevent user input in HTML

Currently, I am working on creating the 8 puzzle box game using JavaScript and jQuery Mobile. The boxes have been set up with <input readonly></input> tags and placed within a 9x9 table. However, an issue arises when attempting to move a box ...

Kurento's WebRTC feature is currently experiencing difficulties with recording functionality

Currently, I am attempting to capture video using the Kurento Media Server with nodejs. Following the hello-world example provided here, I connected a recorderEndpoint to the webrtcEndpoint and successfully got everything up and running. However, on the se ...

troubleshooting problems with jquery ajax and setInterval

$(document).ready(function() { function refreshBids() { var element = $("#biddingDiv"); element.load("bids.php?id=<?=$userId;?>&init=1&auctionid=<?=$auctionId;?>"+(new Date()).getTime()); } refreshBids(); setI ...

reconfigure keyboard shortcuts in web browser

In the popular web browser Google Chrome, users can quickly jump to the next tab by pressing CTRL + TAB. Is there a way to change or disable this shortcut? The provided code snippet does not seem to work as intended. $(document).keydown(function(e){ ...

Transforming the appearance of web elements using jQuery (graphic)

While there are numerous resources on changing CSS with jQuery, I seem to be having trouble getting my image to hide initially and show up when a menu tab is clicked. Any help would be greatly appreciated! ;) h1 { text-align: center; } .Menu { widt ...

Styling with CSS: Enhancing list items with separators

Is there a way to include a separator image in my list using CSS? li { list-style: none; background-image: url("SlicingImage/button_unselect.png"); height: 53px; width: 180px; } This is the code for the separator image: url("SlicingImage ...

Every time I try to create a new React app, I consistently run into the same error

I keep encountering this error every time I try to create a React app using create-react-app. ...

Ways to create an angularJS $watch function that is able to recognize modifications in styling

I have a rich text box equipped with all the necessary style controls. If I input new text, it saves without any issue. Whenever I modify the content (text) and add styles like color highlighting or bold formatting, the changes are saved successfully. H ...

Will the .replaceWith() method alter the code visible to search engines?

After successfully modifying the content of specific H1 elements to not return the value from a global variable using the following code; <script type="text/javascript"> $(document).ready(function() { $("H1").filter(function() { return $(this).text ...

Utilizing HTML and CSS for Optimal Page Layouts

<div id="pageHeading"> <h1>zisland</h1> <img src="islandpic.jpg" alt="Mountain View" style="width:50px;height:50px"> </div> #pageHeading{ color: #000000; width: auto; height: auto; text-align: center; ...

Passing the index in React Native

I am currently developing a music app utilizing the react-native-track-player library. I have created three components named Clusters, Songlist, and Play. Understanding How the Screen Works The flow of components is as follows: Clusters component -> S ...

Is it possible to deactivate dynamic binding in Vue.js?

I'm curious if there's a way to disable dynamic binding for a specific instance of an attribute that I'm displaying. Imagine I have the following code, utilizing two-way binding: this.$children[0].$data.hits In this scenario, I have a vac ...

Is it possible to leverage both functions and variables within the ng-options expression in Angularjs?

I am faced with a situation where I have 2 select boxes. The first one is used to choose the user type (such as groups or individual), and the second one displays the options based on the selection made in the first box. I was wondering if it is possible t ...

Analyzing elements within an array of objects

Here is an array of objects I have: const cart = [ { group: "group 1", qtd: 12, value: 65, term: 20 }, //index 0 { group: "group 1", qtd: 10, value: 100, term: 20 }, //index 1 { group: "group 1", qtd: 18, value: 40, term ...

How to add an hr tag to a div element in HTML dynamically with JavaScript?

Whenever a user interacts with the search box, I have a list that gets populated. Here is an example of the overall structure: <div id="searchResult"> <div> <a href="#">result1</a> </div> <div> <a href="#">result2 ...

Create an instance using the window object in JavaScript

Having an issue when trying to instantiate a class using the window object. I have a namespace called UTIL and within it, there is a class defined as follows: var UTIL = { Classes : {}}; UTIL.Classes.ObservationVal = function(state, id, type, context, pe ...

Deleting the HTML element

Can someone assist me with my script issue? I am facing a problem: when I open my file on fullscreen (over 768px), and move my pointer around the logo div, nothing happens. However, if I resize my browser to below 768px, then back again above 768px, the ...