Gradually eliminate the background color in one smooth motion

When new messages appear, I want them to be subtly highlighted as users hover over them. The background color will slowly disappear on hover thanks to the CSS code provided below. However, this effect should only happen once, which is why I need to remove the additional class "newmessage" that triggers the background color change. But if I remove this class on hover, I lose the gradual disappearing effect...

.newmessage {
  background-color: rgba(213, 213, 213, 1);
  -webkit-transition: background-color 2s ease-out;
  -moz-transition: background-color 2s ease-out;
  transition: background-color 2s ease-out;
}
.newmessage:hover {
  background-color: rgba(213, 213, 213, 0);
}

Answer №1

To create a smooth transition for the style of an element when hovered, you can use JavaScript to add a specific class just once. This will trigger the transition effect on the element's style. Check out an updated version of your fiddle here

DEMO

var newMessages = document.querySelectorAll('.newmessage');

for (var i = 0, l = newMessages.length; i < l; i++) {
    // Add '.hovered' class on mouseover
    newMessages[i].addEventListener('mouseover', function() {
        this.classList.add('hovered');
    });
}
div {
    background-color: gray;
    height: 50px;
    width: 200px;
    margin-bottom: 5px;
}
.newmessage {
  background-color: rgba(220, 55, 55, 1);
  -webkit-transition: background-color 2s ease-out;
  -moz-transition: background-color 2s ease-out;
  transition: background-color 2s ease-out;
}
/* Use additional class instead of .newmessage:hover */
.newmessage.hovered {
  background-color: rgba(220, 55, 55, 0);
}
<div></div>
<div></div>
<div class="newmessage"></div>

Answer №2

If you're searching for a way to trigger a callback after a transition ends in order to remove a class, you can achieve this with the following methods:

Is there a callback on completion of a CSS3 animation?

Indeed, there is a callback event that can be utilized to handle this scenario. By adding an event listener, you can capture this event. Here is an example using jQuery:

$("#sun").bind('oanimationend animationend webkitAnimationEnd', function() { 
   alert("The animation has finished") 
});

You can also achieve this with pure JavaScript:

element.addEventListener("webkitAnimationEnd", callfunction, false);
element.addEventListener("animationend", callfunction, false);
element.addEventListener("oanimationend", callfunction, false);

For a live demonstration, visit: http://jsfiddle.net/W3y7h/

Credits to @Duopixel

In your specific case, it may be necessary to use transitionend instead of animationend.

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 on how to showcase up to 200 characters from a string

<?php include ($_SERVER['DOCUMENT_ROOT'].'/header.php'); include ($_SERVER['DOCUMENT_ROOT'].'/adtop.php'); if(mysql_num_rows($deals) > 0){ while($row = mysql_fetch_assoc($deals)){ echo '<div id= ...

What is the reason for HereMap factoring in stopOver time when calculating travel time for the destination waypoint?

I am currently working on a request using the HereMap Calculate Route API. Waypoint 0 does not have any stopOver time, but waypoints 1 and 2 do have stopOver times. Below is an example of the request: https://route.ls.hereapi.com/routing/7.2/calculateroute ...

Deactivate the image button when no image has been chosen from the input field

Is it possible to have the image button disabled when no image is selected in the input field? The button should be inactive if an image is not chosen. import { useState } from "react"; const CommentForm = ({ handleSubmit, submitLabel }) => ...

Sending a JavaScript function as a value in a JSON object

I've been working on incorporating a word cloud with click event handler using jQCloud. To achieve this, I need to include a JavaScript function within JSON. Within C#, I have generated the dynamic JSON text: foreach (var r in result) { sbChart. ...

The JSON array data is coming back as undefined

Currently facing an issue with the data sa var data = '[{"idcoupons_tbl":"1","discount_percent":"10"}]'; Every time I attempt to parse and retrieve a discount_percent, ie var result= jQuery.parseJSON(data); alert(result["discount_percent"]); ...

Retrieve from MongoDB the items where the age is greater than 10 using the find function in the learngyoumongo

Currently working my way through the learnyoumongo tutorial and facing a challenge in part 3. The task involves a test database filled with parrots, and the objective is to retrieve the parrots whose age exceeds a specified input value. Despite using Mongo ...

How can one determine the most accurate box-shadow values?

I am trying to extract the precise box-shadow parameters from a CSS style rule generated by the server. My main focus is determining whether the element actually displays a visible shadow or not. There are instances where the shadow rule is set as somethi ...

Calling this.$refs.upload.submit() is not providing the expected response from Element-UI

Currently working with element-ui and attempting to upload a file using the following code: this.$refs.upload.submit(); Is there a way to retrieve the response from this.$refs.upload.submit();? I have attempted the following: .then(response => { t ...

Cross domain tracking pixel implemented using ASP.NET, jQuery, and AJAX technology

Currently, I have a page tracking system that uses $.post(PAIRS-DATA) in JavaScript to send collected information back to the server and load as a tracking pixel. finally { //tracking pixel Response.ContentType = "i ...

IE9 is not recognizing CSS styles

Why are my CSS styles not working in IE 9 but they work in IE 8 and Chrome? In the code snippet below, the style cpHeader is defined in a separate CSS file. Any ideas on why IE 9 is failing to render the styles properly? <asp:Content ID="Content2" Cont ...

What is the best way to substitute spaces with underscores in JSON data and incorporate hyperlinks for each row in datatables?

I am looking to customize JSON data from the back-end before displaying it using datatables. Firstly, I want to replace the spaces ( ) in the column artist.name with underscore symbols (_). Additionally, I would like to create hyperlinks for each row in th ...

What steps are needed to convert the format to an array in JavaScript?

I have received a value in the format: [["first"],["second"],["third"]] However, I need it to be like this: {"first","second","third"} How can I achieve this using JavaScript? ...

Instructions for removing and recreating an input field along with its parent elements when the value of a Select tag is changed

I currently have a table with four fields, as illustrated below: Semester | Exam Status | GPA | Fee Status My query is regarding the behavior when changing the value in Exam_Status: I noticed that the Select tag-> does not clear automatically. Specifi ...

Navigating through external JSON data in a Node.js and Express application, and rendering the data using Jade

After going through various examples and solutions in related questions on StackExchange in an attempt to solve my issue, I have decided to post my question. My ultimate goal is to access complex JSON data via an API and REST. I intend to import this data ...

What is the process of utilizing an npm package as a plain JavaScript library through require and module export?

Hey there, I'm a bit unsure if I'm on the right track with my question, but here it goes: What steps do I need to take to modify a node.js package for use as a standalone embedded script/library in HTML? How can I invoke a class constructor in ...

Having trouble accessing the value of null and adding it to an array

Having trouble with a 'value' of null error that is not getting resolved even after window.onload = function(){ Any suggestions on what to do? Here's the code snippet: window.onload = function(){ var shashank = document.getElementB ...

Styling the button in jQuery to switch between disabled and enabled

I'm currently working on creating a disabled/enable button style using jQuery. You can check out my demonstration page on Codepen for reference. In the demo, you'll notice a blue submit button. When you input text into the field, the button bec ...

Encountering a React.js issue when attempting to update data

When attempting to update fields with a given drugid, an error occurs. For example, selecting drugid as 1 and clicking the update button results in an error message stating 'localhost:8081/drug/1' not found. In the MongoDB database, there is also ...

How to remove a specific type from a generic type in Typescript without using Exclude<>?

I am looking for a solution to prevent my function from working with Moment objects when storing values in local storage. Currently, the function dynamically stringifies and stores values, but I want to exclude Moment objects from being processed. Here is ...

Checkboxes with dynamic functionalities are not being submitted in the form

I'm struggling with a div element that dynamically populates a list of checkboxes based on a selection from a drop-down list. Although the checkboxes are being populated correctly, the 'pl' parameter is not being successfully passed to the o ...