JS: Looking to add animation with a button click?

Looking for feedback on my code to animate/colorify the div when clicking the 'Animate' button. Any suggestions or additional code are welcome!

This is how my code currently looks:

.anime {
  animation: coloranimate 5s;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: red;
}

@keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

@-webkit-keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anime" class="anime">
</div>
<button>Animate</button>

My goal is to add animation and color changes to the div by simply clicking the 'Animate' button.

Answer №1

To trigger an animation, you can use the .addClass() method on a button click event. Once the class containing the animation properties is added, the animation will automatically start.


Check out the code snippet below:

$('button').click(function() {
  $('#anime').addClass("anime");
});
#anime {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: red;
}

.anime {
  animation: coloranimate 5s;
}

@keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

@-webkit-keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anime">
</div>
<button>Animate</button>

Answer №2

Trigger a class addition upon clicking via javascript on the #anime element, resulting in an animated effect ...

$('.myButton').on('click', function(){
    $('#anime').addClass('animate-now');
});
.anime {
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: red;
}

@keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

@-webkit-keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

.anime.animate-now {
  animation: coloranimate 5s;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anime" class="anime">
</div>
<button class="myButton">Animate</button>

Answer №3

If you want to achieve your requirement, make sure to incorporate jQuery.

Feel free to test out the following code as it might be helpful for you.

Edit

This snippet focuses on utilizing plain javascript.

function addAnime() {
var classadd = document.getElementById('anime');
classadd.className = 'anime';
}
.anime {
  animation: coloranimate 5s;
  width: 100px;
  height: 100px;
  border: 1px solid black;
  background: red;
}

@keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}

@-webkit-keyframes coloranimate {
  from {
    background: green;
  }
  to {
    background: yellow;
    border: 4px solid black;
  }
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="anime" class="">
</div>
<button onclick="addAnime()">Animate</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

Setting up angular-cli project for rc5- Step by step guide

Trying to integrate angular-cli with angular 2 rc5 but facing challenges: The issue of 'Promise' not being found After attempting to install 'npm install -g angular-cli@webpack', typings did not get installed, resulting in WebStorm un ...

It is not possible to dynamically change the value of a checkbox using jQuery when it is checked or

When the checkbox value is changed to 1, it cannot be changed back to 0 when unchecked. $('.ChkBox').change(function() { if ($(this).attr('checked')) { $(this).val('1'); } else { $(this).val('0'); } ...

Exploring the functions of `map` and `filter` in the world of

Consider this input: var m = [{ name: 'foo', routes: [{verb: 'post', path: '/foo1'}, {verb: 'get', path: '/foo2'}] }, { name: 'bar', routes: [{verb: 'put', path: ...

Is there a way to return two separate functions within a single function that can be rendered as two distinct components in a React application without one function overriding the other?

I'm currently working on a react header that uses conditional rendering to show different elements based on the URL or user login status. However, I'm facing an issue where only one button is being rendered instead of two side by side in my defau ...

What is the best way to align an image underneath text?

I'm currently working on this design concept: https://i.stack.imgur.com/wJm0t.png Below the title, there is a particle image with half square images positioned on the top right and bottom left corners. My goal is to center the particle image below th ...

Accessing React Context globally using the useContext hook

I'm feeling a bit puzzled about how the useContext hook is intended to function in a "global" state context. Let's take a look at my App.js: import React from 'react'; import Login from './Components/auth/Login'; import &apos ...

Solving template strings in a future context

I have a unique use-case scenario where I am filling the innerHTML like this. However, my issue lies in resolving the template literal within the context of a for loop. Any suggestions on how to accomplish this? var blog_entries_dom = 'blog_entries& ...

@media query not functioning properly with certain rules

I've hit a roadblock because my @media query is functioning properly for the initial rule, but fails to work for subsequent rules. For instance, I managed to make the "subButton" disappear when the screen size decreases below the specified width. How ...

What is the best way to eliminate the header and side navigation in a master page design?

I've set up a master page called wrap.master which is connected to multiple content pages. I'm looking to create a new content page and link it to the master page. However, I want this new content page to be independent from the header and side n ...

Send in 3 sets of HTML forms along with a single JavaScript button to save all data in a single row within

I'm facing an issue with submitting multiple forms on a page without submit buttons. I have a script that submits all three forms at the same time, but it's creating separate rows in the database instead of one combined row. Any suggestions on ho ...

Using Python to extract the audio URL (specifically in mp3 format) from a web player

I have been attempting to extract the URL link from a webpage in order to download the audio as an mp3 file, but so far I have not been successful. Here is the code snippet of the webpage: webpage code Specifically, I am trying to retrieve the value of t ...

Font sizes may vary depending on whether the site is accessed with or without the "www" prefix

There is an odd occurrence on my website where the font size seems to change when viewing both the www version and non-www version. While setting up a 301 redirect is a common solution, I am intrigued by why this discrepancy exists as it is not something ...

Trouble assigning the 'data' attribute to the 'Object' tag using jQuery. [Limited to IE8]

I have encountered a problem when creating an object element dynamically in jQuery to display some content. The code functions perfectly in all browsers except for IE8. Here is the code snippet: j$(document).ready(function(){ j$('.ob ...

What is the best way to programmatically select a checkbox that was created dynamically using jQuery?

I've been scouring the internet trying to find information on what I'm attempting to accomplish, but so far I haven't come across anything helpful. The issue I'm facing is with a form that has a section dynamically added using JavaScri ...

Escaping the setTimeout loop

I'm struggling to find a solution for breaking out of a setTimeout loop. for (var i = 0; i < 75; i++) { setTimeout(function (i) { return function () { console.log("turn no. " + i); if (table.game.playerWon) { con ...

Frames of Animation

Seeking assistance in understanding how to create frame animation using JavaScript or CSS. Attempting to replicate the animation seen on this website. Intrigued by the road animation and unsure if it is achieved using a plugin or just JavaScript and CSS. ...

Tips for implementing an 'exclude' feature in TypeScript without encountering any error notifications

export function omit<T, U extends keyof T>(obj: T, keys: U[]): Omit<T, U> { return Object.keys(obj).reduce( (acc, curr) => (keys.includes(curr as U) ? acc : { ...acc, [curr]: obj[curr] }), {} ) as Omit<T, U>; } Encounter ...

Using PHP to insert data from a form with multiple checkbox selections into a MySQL database

Having a form with various fields like Textinputs, Checkboxes, Radios...and seeking to submit it to a MySQL database. Oddly enough, when I remove the checkboxes HTML and associated PHP code, everything functions properly, and all information is successfull ...

The jquery ajax call only seems to function properly when executed on a local

Currently, I am utilizing jQuery ajax to retrieve data from a back-end method in asp.net using the following code: $.ajax({ cache: false, type: "POST", url: '<%= Page.ResolveUrl("~/Live/Live.aspx/GetViews") %>', content: "j ...

Failed to fetch JSON file using jQuery

When I call a web service, I receive a JSON file. I am attempting to retrieve the data using jQuery and display it on an HTML5 page. When I open the JSON file in a browser at SampleURI, I do get the data. {"employeeList":[{"birthDate":"1948-12-08T00:00:00 ...