Executing keyframes animation in JS or jQuery - javascript

I know that it is possible to set the animation of an element by id either in a stylesheet or in JS from the DOM. The issue is that I want the animation to execute every time a click action on a specific element is performed by the user. Adding the animation to an element's style in JS seems to add it permanently so that the keyframes animation cannot be performed again, (only performed once when the window finishes loading). I also thought about using jQuery's .animate() function however all documentation points to it animating over CSS specific styles and not setting/calling the animation style attribute as if I were to set it using CSS. I want to know the best way of executing my animation over an element when another element is clicked on by the user and consistently executing the animation for each click.
#keyframes fadeInDown {
from {
opacity: 0;
transform: translate(0, -20%);
}
to {
opacity: 1;
transform: translate(0, 0);
}
}
The current way I'm setting animation for an element:
$("#element").css("animation", "fadeInDown 0.5s ease-in 0s 1");

This is a toggling animation using transition and jquery, without using .animate()
$(document).ready(function() {
$('button').click(function() {
var box = $('.box')
box.removeClass("show")
setTimeout(function(){
box.addClass("trans").addClass("show")
setTimeout(function(){
box.removeClass("trans")
},100)
},200)
});
});
.box {
background: red;
height: 50px;
width: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
opacity: 0;
transform: translate(0, -20%);
}
.box.trans {
transition: all 0.7s;
}
.box.show {
opacity: 1;
transform: translate(0, 0);
}
<button>Test</button>
<div class="box show"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

It's my first answer on stack overflow.
I had the same question about animation.
What I did last was just like Vivek Patel's answer, but instead of toggling the css keyframe, I created a separated class only for css animation("animation-fadeInDown"), and toggle it.
Because the animation-name "fadeInDown" is correponding to the #keyframes name, so if you separate it you could apply the animation to other elements, by just toggling the animation class.
And, you can still do the css deco to the original box seperately, which might be more clear to read.
I hope this is close to what you looking for.
$('button').click(() => {
$('.box').toggleClass('animation-fadeInDown');
});
.box {
width: 50px;
height: 50px;
background: black;
}
.animation-fadeInDown {
animation: fadeInDown 0.5s ease-in 0s 1
}
#keyframes fadeInDown {
from {
opacity: 0;
transform: translate(0, -20%);
}
to {
opacity: 1;
transform: translate(0, 0);
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="box"></div>
<button>
Test
</button>

Basically CSS animation only runs once when the page loads. So it is not possible to re-trigger it again. Here is the workaround for your use case: Remove the element from the page entirely and re-insert it.
Try this:
$('button').click(() => {
var oldDiv = $('#animated-div');
newDiv = oldDiv.clone(true);
oldDiv.before(newDiv);
$("." + oldDiv.attr("class") + ":last").remove();
});
#keyframes fadeInDown {
from {
opacity: 0;
transform: translate(0, -20%);
}
to {
opacity: 1;
transform: translate(0, 0);
}
}
.animated-div {
animation: fadeInDown 0.5s ease-in 0s 1
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="animated-div" class="animated-div" style="width: 50px; height: 50px; background: black"></div>
<button>
Test
</button>

This is an simple example that use jquery to animate in Queue as it works in #keyframes. The transition duration and animation duration gives more control on the animation character.
$(document).ready(function() {
$('button').click(function() {
$('.box')
.css('transition', 'all 0.2s')
.animate({ opacity: 0 }, {
duration: 200,
step: function(now) {
$(this).css({ opacity: now });
$(this).css({ transform: 'translate(0, -20%)' });
}
})
.animate({ opacity: 1 }, {
duration: 600,
step: function(now) {
$(this).css({ opacity: now });
$(this).css({ transform: 'translate(0, 0)' });
}
})
});
});
.box {
background: red;
height: 50px;
width: 50px;
position: absolute;
margin-top: 50px;
margin-left: 50px;
}
<button>Test</button>
<div class="box"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>

Related

Use mouseover to add animation on hover

I'm trying to add an animation to an element when someone hover on it.
My thought is to add a class with keyframes and attach an mouseover event listener to it.
The reason I don't use CSS is because I want the animation to be finished even the mouse leave the element before the animation is finished. For example, the mouse is moved out of element when rotating on 180 degree (full animation is 360 degree)
But sadly it's not working and I don't know why...
const item = document.querySelector('#rotate');
item.addEventListener('mouseover',function(e) {
if(item) e.classList.add('rotate');
});
#div {
width: 120px;
height: 120px;
background-color: orange;
}
.rotate {
animation: rotating 1s ease 0s 1 normal forwards;
}
#keyframes rotating {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
<div id='rotate'></div>
You're already on the right path. You can listen for the animationend event on the div and remove the rotate class when the event is fired. I've corrected your example snippet below.
const item = document.querySelector('#rotate');
item.addEventListener('mouseover', function(e) {
if(item) item.classList.add('rotate');
});
item.addEventListener('animationend', function(e) {
if(item) item.classList.remove('rotate');
});
#rotate {
width: 120px;
height: 120px;
background-color: orange;
}
.rotate {
animation: rotating 1s ease 0s 1 normal forwards;
}
#keyframes rotating {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
<div id='rotate'></div>
I would say you were pretty close. firstly you must change #div to #rotate then add the class directly to the item then when animation is done remove the class so that it can run again
const item = document.querySelector('#rotate');
item.addEventListener('mouseover', function(e) {
item.classList.add('rotate');
});
item.addEventListener('animationend', function(e) {
item.classList.remove('rotate');
});
#rotate {
width: 120px;
height: 120px;
background-color: orange;
}
.rotate {
animation: rotating 1s ease 0s 1 normal forwards;
}
#keyframes rotating {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
<div id='rotate'></div>
Doesn't change your code too much.
e refers to the event which is incorrect use of it, you should use this to target the current element
use mouseenter will be better in this sitution when you want to trigger an animation when use hover it .
const item = document.querySelector('#rotate');
item.addEventListener('mouseenter',function(e) {
if(item) this.classList.add('rotate');
});
#rotate {
width: 120px;
height: 120px;
background-color: orange;
}
.rotate {
animation: rotating 1s ease 0s 1 normal forwards;
}
#keyframes rotating {
0% {
transform: rotate(0);
}
100% {
transform: rotate(360deg);
}
}
<div id='rotate'></div>

How do I trigger a CSS keyframe animation by pressing a key on the keyboard? [duplicate]

Naturally, we can create a CSS animation using keyframes, and control it from there.
However, ideally, I would like to trigger this animation from a button click - so the button click would be an event...
#keyframes fade-in {
0% {opacity: 0;}
100% {opacity: 1;}
}
Now, on click, I want to trigger this animation; as opposed to from within the CSS animation property.
see here jsfiddle
if you want your animation to work every time you press the button use this code :
$('button').click(function() {
$(".fademe").addClass('animated');
setTimeout(function() {
$(".fademe").removeClass('animated');
}, 1500);
});
where 1500 is the animation-duration in this case, 1.5s
$('button').click(function() {
$(".fademe").addClass('animated');
setTimeout(function() {
$(".fademe").removeClass('animated');
}, 1500);
});
.fademe {
width: 100px;
height: 100px;
background: red;
}
.fademe.animated {
animation: fade-in 1.5s ease;
}
#keyframes fade-in {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="fademe">
</div>
<button>CLICK ME</button>
EXPLANATION :
on click on the button add class animated ( or any other class ) to the element you want to apply the animation to , .fademe
make a setTimeout(function() to delay the removeClass for the duration of the animation 1.5s or 1500ms
write in CSS the declaration of the animation , #keyframes, and add it to the element with the class added by the JQ .fademe.animated
$("#move-button").on("click", function(){
$("#ship").removeClass("moving");
$("#ship")[0].offsetWidth = $("#ship")[0].offsetWidth;
$("#ship").addClass("moving");
});//
#ship
{
background: green;
color: #fff;
height: 60px;
line-height: 60px;
text-align: center;
width: 100px;
}
#move-button
{
margin-top: 20px;
}
#ship.moving
{
animation: moving 2s ease;
}
#keyframes moving
{
0%{ transform: translate(0px);}
50%{ transform: translate(20px);}
100%{ transform: translate(0px);}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div id="ship">Ship</div>
<button id="move-button">Push</button>
If you want to make the animation happen and always end before allowing the event listener to trigger it again, I would suggest to control the behaviour like this:
// Add this to your event listener
if (!element.classList.contains("myClass")) {
element.className = "myClass";
setTimeout(function() {
element.classList.remove("myClass");
}, 1000); //At least the time the animation lasts
}
There is a toggle method that works just fine for this, hope it helps:
function Fade() {
document.getElementById("box").classList.toggle("animate");
}
#box {
background-color: black;
height: 50px;
width: 50px;
}
.animate {
animation: fademe 0.5s;
}
#keyframes fademe {
from {
opacity: 1;
}
to {
opacity: 0;
}
}
<html>
<head>
<title>
Animation Trigger
</title>
</head>
<body>
<div id="box"></div>
<button onclick="Fade()"> Fade above Box</button>
</body>

Make HTML element disappear with CSS animation

I want to know if there is a way to make an HTML element disappear with an animation of CSS. So when the element gets removed from the page by some script, an animation shall display before the element actually gets removed.
Is this possible in an easy way? Or do I need to set a timer to my script that starts the animation with a duration of X and removes the element after time X?
I would get fancy with keyframes
#keyframes myAnimation{
0%{
opacity: 1;
transform: rotateX(90deg);
}
50%{
opacity: 0.5;
transform: rotateX(0deg);
}
100%{
display: none;
opacity: 0;
transform: rotateX(90deg);
}
}
#myelement{
animation-name: myAnimation;
animation-duration: 2000ms;
animation-fill-mode: forwards;
}
If the script is actually removing the DOM element, I don't believe there's a way to fade it out. I think the timer is your only option.
I use jQuery to implement this.
//jQuery
$(document).ready(function() {
var target = $("#div");
$("#btn").click(function() {
removeElement(target);
});
});
function removeElement(target) {
target.animate({
opacity: "-=1"
}, 1000, function() {
target.remove();
});
}
div {
width: 100px;
height: 100px;
background-color: #000;
}
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
</head>
<body>
<div id="div"></div>
<input type="button" value="fadeout" id="btn">
</body>
</html>
Use transitions like this:
function waithide()
{
var obj = document.getElementById("thisone");
obj.style.opacity = '0';
window.setTimeout(
function removethis()
{
obj.style.display='none';
}, 300);
}
div
{
height:100px;
width :100px;
background:red;
display:block;
opacity:1;
transition : all .3s;
-wekit-transition : all .3s;
-moz-transition : all .3s;
}
<div id="thisone" onclick="waithide()"></div>
I think you would have to do it in two steps. first the animate. Then, after animate is done, remove the elem. See the function below. Perhaps it could be put in a jquery plugin?
<style>
#test{
background: red;
height: 100px;
width: 400px;
transition: height 1s;
}
#test.hide {
height: 0;
}
</style>
<div id="test"> </div>
<button>Hide the Div</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
<script>
$('button').click(function(){
removeWithAnimate('#test');
});
function removeWithAnimate(id){
$(id).addClass('hide');
setTimeout( function(){
$(id).remove()
},1000);;
}
</script>
$('button').click(function() {
removeWithAnimate('#test');
});
function removeWithAnimate(id) {
$(id).addClass('hide');
setTimeout(function() {
$(id).remove()
}, 1000);;
}
#test {
background: red;
height: 100px;
width: 400px;
transition: height 1s;
}
#test.hide {
height: 0;
}
<div id="test"> </div>
<button>Hide the Div</button>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.0/jquery.js"></script>
transition: .5s;
invisible:
opacity: 0;
visible:
opacity: 1;
transition will make it appear and disappear smoothly.

Random animation on Simple Image Slideshow

I want to apply a random animation on my slideshow image. First, I tried adding an animation such as scale but it didn't work as I wanted it to.
Things I want to fix:
Smoothness on fadein
Random animation (can be anything at this point, I just want to see how it's done)
Fiddle: http://jsfiddle.net/jzhang172/e7cLtsg9/1/
$(function() {
$('img').hide();
function anim() {
$("#wrap img").first().appendTo('#wrap').fadeOut(3500).addClass('transition').addClass('scaleme');
$("#wrap img").first().fadeIn(3500).removeClass('scaleme');
setTimeout(anim, 3700);
}
anim();
});
body,
html {
margin: 0;
padding: 0;
background: black;
}
#wrap img {
position: absolute;
top: 0;
display: none;
width: 100%;
height: 100%;
}
.transition {
transition: 10s;
}
.scaleme {
transition: 10s;
transform: scale(1.3);
}
.box {
height: 300px;
width: 500px;
position: relative;
overflow: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<div id="wrap">
<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-1.jpg" />
<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-5.jpg" />
<img src="http://elegantthemes.com/preview/InStyle/wp-content/uploads/2008/11/s-3.jpg" />
</div>
</div>
Here is a sample using CSS animations and jQuery (for achieving the randomness of animations). If you don't wish to use CSS animations and want to stick to transitions + jQuery effects (like fadeIn), you can still adapt this code to support it because the base idea will still remain the same. I am not too comfortable with jQuery effects and have hence stuck to using CSS animations.
Below is an overview of how it is being done (refer inline comments for more details):
Inside a wrapper there are a group of images that are part of the slide-show (like in your demo).
Using CSS #keyframes, a list of animations (one of which would be used randomly) is created in addition to the default fade-in-out animation. This list is also maintained in an array variable (in JS for picking up a random one from the list).
On load, the default fade-in-out animation and one random animation is added to the 1st element.
An animationend event handler is added to all of the images. This event handler will be triggered when the animation on an element ends. When this is triggered, animation on the current element is removed and the default fade-in-out + a random animation is added to the next element.
The animations are added using inline styles because if we add multiple CSS classes each with one different animation, then the animation in the latest class will override the others (that is, they will not happen together).
A loop effect is achieved by checking if the current element has any other img sibling elements. If there are none, the animation is added back to the 1st element.
$(window).load(function() {
$img = $('img'); // the images
var anim = ['zoom', 'shrink', 'move-down-up', 'move-right-left']; // the list of random animations
var rand = Math.floor(Math.random() * 4) + 1; // random number
$img.each(function() { // attach event handler for each image
$(this).on('animationend', function(e) { // when animation on one image has ended
if (e.originalEvent.animationName == 'fade-in-out') { // check the animation's name
rand = Math.floor(Math.random() * 4) + 1; // get a random number
$(this).css('animation-name', 'none'); // remove animation on current element
if ($(this).next('img').length > 0) // if there is a next sibling
$(this).next('img').css('animation-name', 'fade-in-out, ' + anim[rand - 1]); // add animation on next sibling
else
$img.eq(0).css('animation-name', 'fade-in-out, ' + anim[rand - 1]); // else add animation on first image (loop)
}
});
});
$img.eq(0).css('animation-name', 'fade-in-out, ' + anim[rand - 1]); //add animation to 1st element on load
})
#wrapper {
height: 250px;
width: 300px;
position: relative;
}
img {
position: absolute;
z-index: 1;
bottom: 20px;
left: 10px;
opacity: 0;
transform-origin: left top; /* to be on the safe side */
animation-duration: 3s; /* increase only if you want duration to be longer */
animation-fill-mode: backwards; /* fill mode - better to not change */
animation-iteration-count: 1; /* no. of iterations - don't change */
animation-timing-function: ease; /* better to leave as-is but can be changed */
}
#keyframes fade-in-out {
0%, 100% {
opacity: 0;
}
33.33%, 66.66% { /* duration is 3s, so fade-in at 1s, stay till 2s, fade-out from 2s */
opacity: 1;
}
}
#keyframes zoom {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(1.5);
}
}
#keyframes shrink {
0%, 100% {
transform: scale(1);
}
50% {
transform: scale(.5);
}
}
#keyframes move-down-up {
0%, 100% {
transform: translateY(0px);
}
50% {
transform: translateY(50px);
}
}
#keyframes move-right-left {
0%, 100% {
transform: translateX(0px);
}
50% {
transform: translateX(50px);
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="wrapper">
<img src="https://placehold.it/200/000000/ffffff" />
<img src="https://placehold.it/200/ff0000/ffffff" />
<img src="https://placehold.it/200/00ff00/ffffff" />
<img src="https://placehold.it/200/0000ff/ffffff" />
</div>

Sliding and fading a div element

I am trying to animate a div element (slide and fade) with a button click. At first, the element is not visible to a user. When the button is clicked, it will slide to right and fade in. Once the button is clicked again, it will slide to left and fade out. I come up with two solutions, with css and with JQuery.
In the first one, I used JQuery. You can find the example in this JSFiddle 1.
HTML
<button id="my-button">Click me!</button>
<div id="my-modal"></div>
CSS
#my-modal {
opacity: 1;
position: fixed;
top: 50px;
left: 0;
left: -250px;
width: 250px;
height: 100%;
background-color: red;
}
JQuery
$("#my-button").click(function () {
var $modal = $("#my-modal");
$modal.stop(true, true).animate({
left: "toggle",
opacity: "toggle"
}, 1000);
});
Here, everything seems working but it does directly opposite of what I want. It first fades out, and with the second click, it fades in. It is because that the opacity of the element is 1, but if I turn it to 0, nothing happens.
Secondly, I tried to do that with css animation by using key-frames (changing opacity from 0 to 1) but it has also problem. It starts the animation exactly the way I want. However, when I click the button again, it disappears immediately. Here is the JSFiddle 2.
HTML
<button id="my-button">Click me!</button>
<div id="my-modal"></div>
CSS
#my-modal {
opacity: 0;
position: fixed;
top: 50px;
left: 0;
left: -250px;
width: 250px;
height: 100%;
background-color: red;
-moz-transition: all 1s ease;
-webkit-transition: all 1s ease;
-o-transition: all 1s ease;
transition: all 1s ease;
}
.move-my-modal {
-moz-transform: translate(250px, 0px);
-webkit-transform: translate(250px, 0px);
-ms-transform: translate(250px, 0px);
-o-transform: translate(250px, 0px);
}
.animate-opacity {
-webkit-animation: toggle-opacity 1s ease;
-moz-animation: toggle-opacity 1s ease;
-o-animation: toggle-opacity 1s ease;
animation: toggle-opacity 1s ease;
-webkit-animation-fill-mode: forwards;
}
#-webkit-keyframes toggle-opacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
#-moz-keyframes toggle-opacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
#-o-keyframes toggle-opacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
#keyframes toggle-opacity {
0% {
opacity: 0;
}
100% {
opacity: 1;
}
}
JQuery
$("#my-button").click(function () {
var $modal = $("#my-modal");
$modal.toggleClass("move-my-modal");
$modal.toggleClass("animate-opacity");
});
To this end, I have these questions;
1) What are the problems with these two approaches? Is there something that I missed or forgot to use? How can I correct them to meet the requirements that I mentioned at the beginning.
2) Which one is the better way to make this action? Is there any cons or pros of these approaches?
3) Is there any other way to make this action? I am new on this area and I might not notice a simpler way.
You can toggle an .active class to the element and use CSS transitions.
This way, if the browser is old enough to not support animations, it will still work but it won't slow down computers that do not handle animations well.
$("#my-button").click(function () {
$("#my-modal").toggleClass('active');
});
#my-modal.active {
opacity: 1;
left: 0;
}
$("#my-button").click(function () {
$("#my-modal").toggleClass('active');
});
#my-modal {
opacity: 0;
position: fixed;
top: 50px;
left: -250px;
width: 250px;
height: 100%;
background-color: red;
transition: all 1s linear;
}
#my-modal.active {
opacity: 1;
left: 0;
}
<button id="my-button">Click me!</button>
<div id="my-modal"></div>
<!-- jQuery -->
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Categories

Resources