Guide on how to activate a css animation using pure vanilla javascript

Seeking a way to trigger a CSS animation using JavaScript without relying on frameworks like jQuery. I have successfully created the animation using @keyframes. Any suggestions?

Below is the code snippet:

/* Animations */

@keyframes party{
    0% {background-color: red;}
    10% {background-color: orange;}
    20% {background-color: yellow;}
    30% {background-color: green;}
    40% {background-color: blue;}
    50% {background-color: purple;} 
}

@-webkit-keyframes party{
    0% {background-color: red;}
    10% {background-color: orange;}
    20% {background-color: yellow;}
    30% {background-color: green;}
    40% {background-color: blue;}
    50% {background-color: purple;} 
}

Answer №1

One effective way to enhance the functionality is by including the class attribute.

For a practical example, take a look at this demonstration: https://codepen.io/yasgo/pen/zYBgjXN

document.getElementById('box').classList.add('active-animation');
.box {
  width: 50px;
  height: 50px;
  background-color: black;
}

.box.active-animation {
  animation: party 5s infinite;
}

@keyframes party{
    0% {background-color: red;}
    10% {background-color: orange;}
    20% {background-color: yellow;}
    30% {background-color: green;}
    40% {background-color: blue;}
    50% {background-color: purple;} 
}
<div id="box" class="box"></di>

Answer №2

If you're looking to spice up your website with some animation, it's actually quite simple. All you need to do is call the animation function, just like this:

Here's an example of triggering an animation with a button:

function party(){
  document.body.style.animation = 'party 2.5s infinite linear';
}
body{
background-color: purple;
}

@keyframes party{
    0% {background-color: red;}
    10% {background-color: orange;}
    20% {background-color: yellow;}
    30% {background-color: green;}
    40% {background-color: blue;}
    50% {background-color: purple;} 
}

@-webkit-keyframes party{
    0% {background-color: red;}
    10% {background-color: orange;}
    20% {background-color: yellow;}
    30% {background-color: green;}
    40% {background-color: blue;}
    50% {background-color: purple;} 
}
<html>
  <body id="bd">
    <button onclick="party()">Press Me!</button>
  </body>


</html>

I hope this information proves to be useful for you in adding some flair to your website!

Answer №3

let square = document.getElementById('square');
square.style.animation = "celebration 5s infinite";
#square {
  width: 200px;
  height:150px;
  background-color: black;
  margin: 20px auto;
  border-radius: 5px;
}

@keyframes celebration {
    0% {background-color: red;}
    10% {background-color: orange;}
    20% {background-color: yellow;}
    30% {background-color: green;}
    40% {background-color: blue;}
    50% {background-color: purple;} 
}

@-webkit-keyframes celebration {
    0% {background-color: red;}
    10% {background-color: orange;}
    20% {background-color: yellow;}
    30% {background-color: green;}
    40% {background-color: blue;}
    50% {background-color: purple;} 
}
<div id="square"></div>

Answer №4

To apply animation to the desired element, you can simply set the animation property as shown below.

// set the css animation property for spinning effect
const loader = document.getElementById("loader");
loader.style.animation = "spin 2s linear infinite";
/* styling for the loader element */
#loader {
  border: 10px solid black;
  border-top: 10px solid white;
  border-bottom: 10px solid white;
  border-radius: 50%;
  width: 30px;
  height: 30px;
}

/* defining spin animation keyframes */
@keyframes spin {
  0% {
    transform: rotate(0deg);
  }
  100% {
    transform: rotate(360deg);
  }
}
<!-- loader element to be animated -->
<div id="loader"></div>

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

Brick-themed HTML/CSS elements drift away from each other

I'm currently designing an image collage for my website and attempted to use masonry for the layout. However, when I adjust the size of the blocks, they seem to drift apart, creating large gaps between each block. Any suggestions on how to resolve thi ...

Struggling to access component variables within the setTimeout function

As a newcomer to Angular(6), I am facing an issue where I am unable to access component variables within a setTimeout function. Below is the code snippet illustrating my problem. export class ConSellerDraftsolSecOneComponent implements OnInit { ...

Is it advantageous to employ several wrapper-divs inside section elements when working with HTML5 and CSS?

Back in the day, I learned how to create a website by enclosing all content below the body tag within a div with the class "wrapper." This approach made sense as it allowed for easy vertical and horizontal alignment of the entire content. Just yesterday, ...

Adjust the <div> element to dynamically resize based on the user's browser changes

I need a div to adjust its width and height dynamically based on the browser dimensions when a user resizes their browser window. Implemented code following the provided suggestions: <!DOCTYPE html> <html> <head> <link rel="s ...

Is there a way to turn off keyboard input for MUI datepicker V5?

I previously used the DatePicker from @material-ui/date-pickers, which only had a picker option available. Recently, I upgraded to MUI V5 and followed the migration guide provided in this documentation: https://mui.com/x/react-date-pickers/migration-lab/ ...

What is the best way to vertically flip a background image that is repeating along the y axis in CSS?

I am in the process of developing a mobile web app and I need assistance with flipping the background image when it repeats along the y-axis. Can someone guide me on how to achieve this using CSS or JavaScript? https://i.stack.imgur.com/b107V.jpg var el ...

What is the functionality of the reduce() higher-order function?

Here is the reduce() function implementation: function reduce(array, combine, start) { let current = start; for (let element of array) { current = combine(current, element); } return current; } Now, I am tackling this question: ...

I am having trouble getting my HTML to properly link with my CSS while using Chrome OS

My website code is not linking with the CSS file <!DOCTYPE html> <html> <head> <link href="main.css" rel="slylesheet" text="text/css"> <title></title> </head> <body> < ...

Working with Node.js and MySQL can involve using callbacks within nested queries

I am trying to add data to my database only if it doesn't already exist. While attempting this, I encountered an error message: { [Error: Cannot enqueue Query after invoking quit.] code: 'PROTOCOL_ENQUEUE_AFTER_QUIT', fatal: false } My ...

Display a caution when verifying a function's value instead of its return value

I've encountered a common pitfall (especially with autocomplete) while testing a function return value. There are instances when I forget to include the parentheses () at the end, causing it to always return true. class Foo { public bar(): boolea ...

Steps to create a dropdown select option using an AJAX call: When the data is fetched, it generates an array

How can I dynamically populate a dropdown with data from an array using jQuery and AJAX? <html> <script> $(document).ready(function() { $("#class_name").change(function(){ var class_id=$("#class_name").val(); ...

The functionality of ClickMarker is malfunctioning in the XY Amcharts

Recently, I encountered a situation where I had to incorporate custom legends in XY Amcharts. After managing to implement them successfully, I came across an issue. Despite adding event listeners to the legends, the associated function failed to trigger. ...

The fixed left div and scrollable right div are experiencing issues with their alignment

I am having an issue with a section where the left div is fixed and the right div is scrollable. However, the content of the right div scrolls even before the scroll top reaches the section. My goal is for the right div to scroll only when it reaches the t ...

Issues arising from carousel images with varying sizes

I am currently working on an ecommerce project where I am incorporating a carousel feature. The challenge I am facing is that the images within the carousel vary in size, and I would like them all to fit into uniform frames regardless of their original dim ...

The custom font in my Next.js project is functioning perfectly in the development environment, but when I try to build it locally, the font doesn

Incorporating the Amazon Ember font as a custom font in my application has been a bit of a challenge. I followed the necessary steps of setting up a font.ts file in the lib folder and exporting the font correctly, as guided by various blog posts. Initially ...

Creating a rectangular pyramid using three.js r68: a step-by-step guide

Currently working on r68, I'm in search of a modern example showcasing the creation of a rectangular pyramid that will allow me to implement THREE.MeshFaceMaterial(). Many existing examples are outdated and lead to errors with my current setup. My re ...

Guide on accessing elements such as inputs and selects in a changing form

I'm using a dynamic form that creates fields on the fly when the "+" button is clicked. This form isn't hardcoded into the document, but rather generated when the button is pressed. I'm wondering how I can access the form values. Should I ...

Table cell featuring a status menu created with Material UI DataGrid

I'm looking to include a column called "Filled Status." Although I've checked the documentation, I can't quite figure out how to do it. It seems like I may need to use renderCell when setting up the column, but I'm not sure how to make ...

What is the reason for property x not appearing on type Y despite module augmentation efforts?

I've been experimenting with modules and came across a scenario that I'm struggling to fully understand. This is how I have everything set up: import MyTesterImpl from "./MyTesterImpl"; declare module "./MyTesterImpl" { int ...

How can I retrieve all values from an input number field that is created using *ngFor in Angular?

In my table, I have a list of cart products displayed with a quantity field. Users can increase or decrease the quantity using options provided. Currently, if I place an update button inside a loop, it creates separate buttons for each product. However, I ...