What is the best way to activate a CSS animation?

I've hit a roadblock while attempting to trigger a CSS animation.

Here's my CSS:

h3[id="balance-desktop"]{
    color: black;

    -webkit-animation-name: gogreen;
    -webkit-animation-duration: 2s;
    animation-name: gogreen;
    animation-duration: 2s
}

/* Safari 4.0 - 8.0 */
@-webkit-keyframes gogreen {
    from {color: black;}
    to {color: limegreen;}
    from{color: limegreen;}
    to{color: black;}
}

/* Standard syntax */
@keyframes gogreen {
    from {color: black;}
    to {color: limegreen;}
    from{color: limegreen;}
    to{color: black;}
}

It's a simple animation that changes the color of an h3[id=balance-desktop] element.

The animation works when the page loads. I'm trying to make it work when I call my JavaScript function, but so far, no success.

Attempt #1:

function showGreenAnimation(){
    var test = document.getElementById("balance-desktop");
    test.style.webkitAnimationName = 'gogreen';
    test.style.webkitAnimationDuration = '4s';
}

Attempt #2:

function showGreenAnimation(){
    document.getElementById("balance-desktop").style.webkitAnimationName = "";
    setTimeout(function ()
    {
        document.getElementById("balance-desktop").style.webkitAnimationName = "gogreen";
    }, 0);
}

I've tried all the solutions recommended on How to activate a CSS3 (webkit) animation using JavaScript?, but none have worked for me.

Is there something incorrect in my code?

Answer №1

After reviewing your second attempt, it appears to be functioning properly. I made some adjustments to tidy up your code by removing outdated webkit prefixes. Initially, I set the animationName to 'none' inline and then removed it, allowing the element to revert back to its original CSS animation name.

Furthermore, I restructured the keyframe animation to utilize percentages rather than multiple from and to values.

var btn = document.getElementById("button");
var text = document.getElementById("balance-desktop");

function turngreen() {
  text.style.animationName = 'none';
  setTimeout(function() {
    text.style.animationName = null;
  }, 0);
}

btn.addEventListener('click', turngreen);
#balance-desktop {
  color: black;
  animation: gogreen 2s;
}

@keyframes gogreen {
  0%, 100% { color: black; }
  50% { color: limegreen; }
}
<h3 id="balance-desktop">Heading</h3>

<button id="button">Turn Green</button>

Answer №2

If you're looking for a simpler solution, consider using a CSS Transition.

All modern browsers now support CSS3 Animations and Transitions, so there's no need to include vendor prefixes unless you are targeting older browsers.

// To implement a transition function, first get references to DOM elements:
var btn = document.querySelector("button");
var h3 = document.querySelector(".balance-desktop");

// Create an event listener that triggers the transition function when the button is clicked.
btn.addEventListener("click", function(){

  // By changing a style property on the element configured for transitions,
  // the transition effect will be activated.
  h3.classList.add("goGreen");
  
  // Once the transition is complete, remove the added style to trigger
  // a transition back to the original style. Ensure the delay is at least
  // equal to the duration of the transition (2 seconds in this case).
  setTimeout(function(){
    h3.classList.remove("goGreen");
  },2000);
});
.balance-desktop{
    color: black;
    /* Apply a transition effect over 2 seconds to all properties with changes. */
    transition:2s all;
}

.goGreen {
 color: limegreen;
}
<h3 class="balance-desktop">Hello</h3>
<button>Run Function</button>

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

Retrieving information from a JSON source to populate a data table

Hello fellow developers... I'm currently facing an issue while trying to dynamically populate a data table with information fetched through a fetch request and stored in a Vuex instance variable. Here is the relevant code snippet: <script> impo ...

What is the best way to set up Flow type checking for functions passed as props in a React and Redux application?

In my app, I've been passing Redux action creators as props and want to improve type checking. Using the generic Function type has limitations, so I tried using the existential operator (*) in my Props type with no success in getting Flow to infer the ...

Load the dropdown menu in the select element using the AngularJS $ngresource promise

I have a select box on my webpage that I need to fill with data received from a server. I am currently using a service to fetch this data, but I'm unsure how to access the values returned from the promise and populate the ng-options in the select tag. ...

Executing a Component function within an "inline-template" in VueJS

VueJS version 1.9.0 app.js require('./bootstrap'); window.Vue = require('vue'); Vue.component('mapbox', require('./components/mapbox.js')); const app = new Vue({ el: '#app' }); components/mapbox.js ...

Tips for sending an array of input field values through an Ajax request

In my current web form, there is a dynamic option that adds rows with the same attributes. These rows need to be submitted through an Ajax call to my PHP for insertion into the database. Access: <tr> <td><input type"text" name="access[nam ...

Is it possible to rewrite this function recursively for a more polished outcome?

The function match assigns a true or false value to an attribute (collapsed) based on the value of a string: function match(children) { var data = $scope.treeData for (var i = 0; i < data.length; i++) { var s = data[i] for (var ...

Error: Express JS custom module cannot be located in the root directory's modules folder

The file structure of my express js app resembles this I'm attempting to load a modules folder from the root directory. routes/users.js var express = require('express'); var router = express.Router(); var md=require('./modules') ...

Exploring the functionality of the $.each jQuery iterator. Can someone clarify the distinctions between these two methods?

Having vertices as an array of google.maps.LatLng objects means that they should return latlng points. The first code snippet works perfectly fine, however, I encounter issues when using the second one. // Iterate over the vertices. for (var index =0; ind ...

Adjust the text appearance of the graph in ApexCharts

Is there a way to adjust the font size of the donut chart generated by using apexchart? You can view the image here. <template> <section> <v-card raised> <v-card-title class="blue--text">Requests Overview</v-card-ti ...

What is the best way to retrieve the checkbox value using AJAX/jQuery with a Spring form?

My form contains a group of checkboxes identified by the path deliveryStatus, like so: <form:checkbox path="deliveryStatus" value="notDelivered"/> <form:checkbox path="deliveryStatus" value="delivered"/> I came across two helpful examples: E ...

The UL list-style does not seem to be working properly on the Woocommerce checkout page

After creating my e-commerce website and implementing the woocommerce plugin to display products, I encountered an issue. The main menu pages are all showing up with the list-style, but the pages associated with the plugins are not displaying the list-styl ...

Injecting multiple instances of an abstract service in Angular can be achieved using the following techniques

I am fairly new to Angular and currently trying to make sense of the code written by a more experienced developer. Please excuse me if I'm not adhering to the standard communication practices and vocabulary. There is an abstract class called abstract ...

Executing XSS Reflected Attack by Loading an External JS Script via POST Parameter

Experimenting with XSS attacks on my vbox machines, just for kicks! I have two .html files - one works and the other doesn't. The file that works contains: <html> <head></head> <body> <form method="post" action=&q ...

Using Javascript to upload an image and show it in a small display

Hey there, I have a functioning JavaScript code that loads an image uploaded by the user onto the HTML page. However, the issue is that the image doesn't have a set maximum height or width, causing buttons on the page to move out of view and become in ...

Is there a tool or software available that can securely encode a text file into an HTML file without the need for loading it using AJAX?

At the moment, I'm using jQuery to load a txt file (in utf-8) via $.ajax. The txt file has some break lines, such as: line1 line2 line3 When loaded through AJAX into a variable, it appears as: line1\n\nline2\nline3 I could manuall ...

Stop horizontal overflow of content

This unique Vuetify demo on CodePen showcases a two-column layout. The first column contains a <v-list> enclosed in a green <v-alert>. By clicking the "toggle text" button, you can switch the title of the first list item between short and long ...

Every time I click a button, I am trying to add JSON objects into an array and then show the outcomes

Currently, my goal is to create a random selection feature from an array that users can contribute to by clicking a button. I am a bit unsure about how to proceed with this task. The application is developed in React and it utilizes the movieDB's API ...

Dynamic resizing of Bootstrap Carousel

As I delve into the realm of web design, I've encountered a puzzling issue with my BootStrap Carousel on a website project. Despite copying the code directly from the BootStrap 5.1 carousel documentation page, its behavior is rather odd, and I'm ...

When hovering over a circle in CSS with a background image to hide text, the shape becomes distorted

I am attempting to create a series of circles with background images and accompanying text displayed side by side. My goal is to have the image opacity change and the text disappear upon hovering over each circle. Additionally, I do not want underlines to ...

Unable to Get Basic jQuery .load Example to Function

Seeking assistance with a jQuery issue regarding loading HTML snippets into a page. When the snippet contains just HTML, it loads fine. However, when it includes a script, there seems to be an issue. Simplified code provided below for better understandin ...