Attempting to initiate a CSS animation by clicking a button using JavaScript

I'm having trouble getting a CSS animation to trigger with a button press using Javascript. I've gone through various questions and answers, but nothing seems to work. My code looks like it should do the trick -- what am I missing? When I click the button, I expect the background color of a specified div to change over 2 seconds to light blue. I've attempted changing the color of both the Body and Test div, but nothing happens. The alert() function is working fine, which adds to my confusion as it's in the same function as the colorChange script.

<!DOCTYPE html>
<html lang="en">
  <head>
    <title>&lt;model-viewer&gt; example</title>
    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />
    <meta name="viewport" content="width=device-width, initial-scale=1" />

    <script>
      function colorChange() {
        alert("The button works");
        document.getElementByID('test').style.animation="changeColor";
      }
    </script>

    <style>
      body {
        background-color: darkblue;
        -webkit-transition: all 2s ease;
        -moz-transition: all 2s ease;
        -o-transition: all 2s ease;
        -ms-transition: all 2s ease;
        transition: all 2s ease;
      }
      
      .test {
        width: 500px;
        height: 500px;
        background-color: pink;
      }

      @keyframes changeColor {
        to {
          background-color: lightblue;
        }
      }
    </style>
  </head>

  <body id="body">
    <div class="test"></div>
    
    <button id="button" onclick="colorChange()">test animation</button>
  </body>
</html>

Answer №1

There appear to be a few issues within the code snippet.

One problem is the absence of an element with the id 'test'. Even when attempting to target the element with the class name 'test' using document.querySelector('.test'), the animation fails to execute.

The main reason for this failure is that animations require a specified duration; otherwise, the default time of 0 seconds will prevent the animation from starting.

Below is the revised code, now including a 10-second duration in the style.animation property:

function colorChange() {
        //alert("The button works");
        document.querySelector('.test').style.animation="changeColor 10s";
      }
      body {
        background-color: darkblue;
        -webkit-transition: all 2s ease;
        -moz-transition: all 2s ease;
        -o-transition: all 2s ease;
        -ms-transition: all 2s ease;
        transition: all 2s ease;
      }
      
      .test {
        width: 500px;
        height: 500px;
        background-color: pink;
      }

      @keyframes changeColor {
        to {
          background-color: lightblue;
        }
      }
    <div class="test"></div>
    
    <button id="button" onclick="colorChange()">test animation</button>

Answer №2

Initially, there seems to be a typo in your JavaScript function. It ought to be 'getElementById'. Additionally, keep in mind that test is a class, not an id. Consequently, you can either switch it to an ID or utilize the function: 'document.getElementsByClassName("test")' or 'document.querySelector(".test")' to gain access to it.

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 best way to invoke a Servlet from within a d3.json() function

Currently, I am using d3 to create charts with nodes and links connecting them. In order to retrieve the data, I have used a json file named link.json and accessed it using the following code: d3.json("link.json", function(error, graph) {} Although this ...

The button can only be edited using Internet Explorer

My webpage features a button that displays correctly in Chrome, but the text inside the button gets cut off when viewed in IE (see image). Can you provide guidance on what might be causing this issue and how to resolve it? Bootstrap version 4.0.0 is also b ...

Sustaining the hover effect background color when hovering over submenu options

I am currently working on a navigation menu that includes list items a, b, c, d, e, f. One issue I am facing is when a user hovers over the list item d, the submenu items like d1, d2, d3, d4, and d5 appear within the d section. However, the background col ...

What steps can I take to prevent Internet Explorer from caching my webpage?

After implementing Spring MVC for Angular JS on the front end, I encountered an issue where logging in with different user credentials resulted in incorrect details being displayed. This problem only occurred in Internet Explorer, requiring me to manually ...

Tips for capturing all mobile events in Angular

Trying to capture all mobile events like touch and swipe, I have added event listeners at the document level: document.addEventListener('tap', trackTouchActivity, false); document.addEventListener('swipe', trackTouchActivity, false ...

Tips for Deactivating One Button While Allowing Others to Remain Active

Whenever the $order_status is marked as Accepted, only the button labeled Accept should be disabled. If the $order_status changes to Dispatched, then the button that should be disabled is labeled as Sent. However, if the status is Cancelled, then the butto ...

Extract words with specified tags from HTML using Python and return them as a list

Is there a simple way to parse HTML, extract the text, and generate a list of tags associated with each word or snippet of text? For instance, in the given HTML code: <em>Blah blah blah</em> blah again <i>and then again</i> The de ...

Obtain a specific element in Puppeteer JS by utilizing the waitForSelector function to detect when its class name changes

I am faced with a situation where I need to wait for a specific element to change its classes dynamically. The challenge arises when utilizing the waitForSelector function, as it fails to work when no new element is added to the DOM. Instead, it is the &l ...

Modifying CSS stylesheet does not alter the background color

body { background-color: bisque; } <!DOCTYPE html> <html> <head> <title>Reading</title> </head> <body> <h1> <button><a href="index.html">Home</a></button> & ...

Enhance your user interface by customizing the expand icon in the React material

Currently, I am utilizing Material-table with a focus on Tree-data. You can find detailed information about this feature here: https://material-table.com/#/docs/features/tree-data. While attempting to implement the provided example, I am encountering diff ...

What is the best way to remove headers and footers programmatically in print pages on Safari using JavaScript?

Struggling with eliminating the header and footer on print pages in Safari using JavaScript? While disabling the header and footer manually can be done through print settings in most browsers, my aim is to automate this process with code to ensure that use ...

Creating an autocomplete feature with Materialize.css that opens the list automatically without any minimum input length requirement

When using Materialize.css autocomplete, I am trying to make the list open upon focusing the textbox without entering any characters. I attempted to achieve this by setting {minLength: 0}: $('#dataset_input').autocomplete({data: res, limit: 20, ...

Having trouble with Typescript accurately converting decimal numbers?

I am struggling with formatting decimals in my Typescript class. export myclass { deposit: number; } After converting my web API class to this Typescript class, my decimal amounts lose their additional zero. For example, 1.10 becomes 1.1. I want to keep ...

React component with element style declared in module.css file and conditional state

I'm in the process of developing a mobile dropdown feature for a React web application. I am looking for guidance on the proper syntax to use when incorporating multiple classes into a React element. My goal is to apply styles from an imported module ...

JQUERY inArray failing to find a match

I'm at my wit's end working with inArray and I'm really hoping for some help. I am using AJAX to fetch userIDs from my database, which come through as a JSON-encoded array. However, no matter what I try, I always get a -1 when trying to mat ...

Issue: Stylesheet not being loaded on Index.html through Gulp

Issue The .css file is not being loaded by the index.html despite setting up a gulp.js file. It seems like the folder directory might be causing the problem. However, the .scss files in the /src/scss folder are compiling correctly into CSS within the /bui ...

Using shadow effects on the <Grid> component with Material UI

Is there a way to implement the box-shadow property on a <Grid> component in Material UI? I've gone through the official documentation regarding Shadows - Material UI, but I'm struggling to grasp how it can be applied to a <Grid>. De ...

Move items between unordered lists with automatic saving

As someone who is new to javascripting and php, I am looking to create multiple lists where I can easily drag and drop items between them. The specific order of the items within each list is not crucial as I will be able to adjust it using SORT BY. While ...

What is the best way to maintain the height of a table row while applying a CSS border to a cell within that row?

I am working on a jQuery script that selects a cell when clicked, and I want the row to maintain its height without changing. Even though I have set the height of the table row using CSS, whenever I change the border of a single cell, the entire row' ...

Expanding size on hover without affecting the alignment of surrounding elements

Imagine there are 10 divs on the page styled as squares, collectively known as the home page. Among these 10: 3 divs belong to the .event1 class, 5 divs belong to the .event2 class, and 2 divs belong to the .event3 class. <div class="boxes event1"> ...