Pointer Class Freezes when User is Idle - javascript

I "attached" a keyframe animation to my mouse pointer. Ideally, a pulse should appear around the mouse when the user is idle for 2 seconds, then disappear when they become active. I'm toggling the "pulse" class's visibility. There are two problems:
The keyframe animations is no longer attached to the mouse movement
when the user becomes idle, the animation will appear at any stage of the pulse. It may be very small and faint or thick and opaque, but the ring will be static until the user moves again:
var TimeoutID;
function inputdetect() {
// attaches event handler to specified event
// takes event as string, function to run, and optional boolean
// to indicate when the event propogates
// these are false, so events "bubble up"
this.addEventListener("mousemove",resetTimer,false);
this.addEventListener("mousedown",resetTimer,false);
this.addEventListener("mousewheel",resetTimer,false);
this.addEventListener("keypress",resetTimer,false);
this.addEventListener("touchmove",resetTimer,false);
this.addEventListener("DOMmousescroll",resetTimer,false);
this.addEventListener("MSpointermove",resetTimer,false);
startTimer();
}
inputdetect();
function startTimer() {
//waits two seconds before calling inactive
TimeoutID = window.setTimeout(goInactive,2000); // does it need to take the window variable??
}
function resetTimer(e) {
window.clearTimeout(TimeoutID);
goActive();
}
function goActive() {
//what happens when the UI is not idle
$('p').text("The UI is not idle.");
$('.cursory').css("background-color","green");
$('.pulse').css('visibility','hidden');
startTimer();
}
function goInactive() {
$('p').text("The UI is idle.");
// REPLACING CURSOR WHEN UI IS IDLE
//this part won't work
$('.cursory').css("background-color","red");
$('.pulse').css('visibility','visible');
}
// THIS changes the pointer to a css element
$(document).ready(function() {
$(document).on('mousemove', function(e) {
$('.cursory').css({
left: e.pageX,
top: e.pageY
});
});
});
html {
cursor: none;
}
.cursory {
height: 10px;
width: 10px;
border-radius: 100%;
margin: 0px;
padding: 5px;
background-color: green;
background-clip: content-box;
position: fixed;
}
.pulse {
border: 3px solid blue;
-webkit-border-radius:30px;
height:18px;
width:18px;
position: fixed;
z-index:-1;
left:-7px;
top:-7px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
#-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div class = "cursory"><div class = "pulse"></div></div>
<!--this is where the HTML will go*/-->
<p>hello</p>
emphasized text

Add another class to .pulse. And attach the animation to that class. When you don't want animation just remove the class. On reapplying the class animation will start from starting point so you won't see any inconsistency.
Plus to be sure about you animation you give visibility: hidden; to .pulse. but give visibility: visible; in your additional class and mention your additional class like this .pulse.additionalClass. It will override your .pulse's visibility: hidden

#shishir-trivedi Okay, I tried adding the animation to the pulse class and:
var TimeoutID;
function inputdetect() {
// attaches event handler to specified event
// takes event as string, function to run, and optional boolean
// to indicate when the event propogates
// these are false, so events "bubble up"
this.addEventListener("mousemove",resetTimer,false);
this.addEventListener("mousedown",resetTimer,false);
this.addEventListener("mousewheel",resetTimer,false);
this.addEventListener("keypress",resetTimer,false);
this.addEventListener("touchmove",resetTimer,false);
this.addEventListener("DOMmousescroll",resetTimer,false);
this.addEventListener("MSpointermove",resetTimer,false);
startTimer();
}
inputdetect();
function startTimer() {
//waits two seconds before calling inactive
TimeoutID = window.setTimeout(goInactive,2000); // does it need to take the window variable??
}
function resetTimer(e) {
window.clearTimeout(TimeoutID);
goActive();
}
function goActive() {
//what happens when the UI is not idle
$('p').text("The UI is not idle.");
$('.cursory').css("background-color","green");
$('.cursory').removeClass("pulse");
startTimer();
}
function goInactive() {
$('p').text("The UI is idle.");
// REPLACING CURSOR WHEN UI IS IDLE
//this part won't work
$('.cursory').css("background-color","red");
$('.cursory').addClass("pulse");
}
// THIS changes the pointer to a css element
$(document).ready(function() {
$(document).on('mousemove', function(e) {
$('.cursory').css({
left: e.pageX,
top: e.pageY
});
});
});
html {
cursor: none;
}
.cursory {
height: 10px;
width: 10px;
border-radius: 100%;
margin: 0px;
padding: 5px;
background-color: green;
background-clip: content-box;
position: fixed;
}
.pulse {
border: 3px solid blue;
-webkit-border-radius:30px;
height:18px;
width:18px;
/*position: fixed;*/
z-index:-1;
left:-7px;
top:-7px;
-webkit-animation: pulsate 1s ease-out;
-webkit-animation-iteration-count: infinite;
opacity: 0.0
}
#-webkit-keyframes pulsate {
0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
50% {opacity: 1.0;}
100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<div class = "cursory"></div>
<!--this is where the HTML will go*/-->
<p>hello</p>
now the whole thing pulses. How do I make the inner circle remain the same size? I've been working on this for a few days. I'm very new to both CSS and jQuery, so please be patient with me.
I thought separating them into separate classes then attaching them would align their actions while keeping their specs separate but it appears to have mashed the .cursor class into the .pulse class.

Related

how to use if statement inside an event listener? [duplicate]

I have a CSS3 animation that needs to be restarted on a click. It's a bar showing how much time is left. I'm using the scaleY(0) transform to create the effect.
Now I need to restart the animation by restoring the bar to scaleY(1) and let it go to scaleY(0) again.
My first attempt to set scaleY(1) failed because it takes the same 15 seconds to bring it back to full length. Even if I change the duration to 0.1 second, I would need to delay or chain the assignment of scaleY(0) to let the bar replenishment complete.
It feels too complicated for such a simple task.
I also found an interesting tip to restart the animation by removing the element from the document, and then re-inserting a clone of it:
http://css-tricks.com/restart-css-animation/
It works, but is there a better way to restart a CSS animation?
I'm using Prototype and Move.js, but I'm not restricted to them.
No need in timeout, use reflow to apply the change:
function reset_animation() {
var el = document.getElementById('animated');
el.style.animation = 'none';
el.offsetHeight; /* trigger reflow */
el.style.animation = null;
}
#animated {
position: absolute;
width: 50px; height: 50px;
background-color: black;
animation: bounce 3s ease-in-out infinite;
}
#keyframes bounce {
0% { left: 0; }
50% { left: calc( 100% - 50px ); }
100% { left: 0; }
}
<div id="animated"></div>
<button onclick="reset_animation()">Reset</button>
Just set the animation property via JavaScript to "none" and then set a timeout that changes the property to "", so it inherits from the CSS again.
Demo for Webkit here: http://jsfiddle.net/leaverou/xK6sa/
However, keep in mind that in real world usage, you should also include -moz- (at least).
#ZachB's answer about the Web Animation API seems like "right"™ way to do this, but unfortunately seems to require that you define your animations through JavaScript. However it caught my eye and I found something related that's useful:
Element.getAnimations() and Document.getAnimations()
The support for them is pretty good as of 2021.
In my case, I wanted to restart all the animations on the page at the same time, so all I had to do was this:
const replayAnimations = () => {
document.getAnimations().forEach((anim) => {
anim.cancel();
anim.play();
});
};
But in most cases people will probably want to select which animation they restart...
getAnimations returns a bunch of CSSAnimation and CSSTransition objects that look like this:
animationName: "fade"
currentTime: 1500
effect: KeyframeEffect
composite: "replace"
pseudoElement: null
target: path.line.yellow
finished: Promise {<fulfilled>: CSSAnimation}
playState: "finished"
ready: Promise {<fulfilled>: CSSAnimation}
replaceState: "active"
timeline: DocumentTimeline {currentTime: 135640.502}
# ...etc
So you could use the animationName and target properties to select just the animations you want (albeit a little circuitously).
EDIT
Here's a handy function that might be more compatible using just Document.getAnimations, with TypeScript thrown in for demonstration/fun:
// restart animations on a given dom element
const restartAnimations = (element: Element): void => {
for (const animation of document.getAnimations()) {
if (element.contains((animation.effect as KeyframeEffect).target)) {
animation.cancel();
animation.play();
}
}
};
Implement the animation as a CSS descriptor
Add the descriptor to an element to start the animation
Use a animationend event handler function to remove the descriptor when the animation completes so that it will be ready to be added again next time you want to restart the animation.
HTML
<div id="animatedText">
Animation happens here
</div>
<script>
function startanimation(element) {
element.classList.add("animateDescriptor");
element.addEventListener( "animationend", function() {
element.classList.remove("animateDescriptor");
} );
}
</script>
<button onclick="startanimation(
document.getElementById('animatedText') )">
Click to animate above text
</button>
CSS
#keyframes fadeinout {
from { color: #000000; }
25% {color: #0000FF; }
50% {color: #00FF00; }
75% {color: #FF0000; }
to { color : #000000; }
}
.animateDescriptor {
animation: fadeinout 1.0s;
}
Try it here: jsfiddle
If you have a class for CSS3 animation, for example .blink, then you can removeClass for some element and addClass for this element thought setTimeout with 1 millisecond by click.
$("#element").click(function(){
$(this).removeClass("blink");
setTimeout(function(){
$(this).addClass("blink);
},1 // it may be only 1 millisecond, but it's enough
});
You can also use display property, just set the display to none.
display:none;
and the change backs it to block (or any other property you want).
display:block;
using JavaScript.
and it will work amazingly.
The Animation API gives you full control over when and what to play, and is supported by all modern browsers (Safari 12.1+, Chrome 44+, Firefox 48+, Edge 79+) .
const effect = new KeyframeEffect(
el, // Element to animate
[ // Keyframes
{transform: "translateY(0%)"},
{transform: "translateY(100%)"}
],
{duration: 3000, direction: "alternate", easing: "linear"} // Keyframe settings
);
const animation = new Animation(effect, document.timeline);
animation.play();
Demo: https://jsfiddle.net/cstz9L8v/
References:
https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/KeyframeEffect
https://developer.mozilla.org/en-US/docs/Web/API/Animation
There is an answer on MDN, which is similar to the reflow approach:
<div class="box">
</div>
<div class="runButton">Click me to run the animation</div>
#keyframes colorchange {
0% { background: yellow }
100% { background: blue }
}
.box {
width: 100px;
height: 100px;
border: 1px solid black;
}
.changing {
animation: colorchange 2s;
}
function play() {
document.querySelector(".box").className = "box";
window.requestAnimationFrame(function(time) {
window.requestAnimationFrame(function(time) {
document.querySelector(".box").className = "box changing";
});
});
}
If you create two identical sets of keyframes, you can "restart" the animation by swapping between them:
function restart_animation(element) {
element.classList.toggle('alt')
}
#keyframes spin1 {
to { transform: rotateY(360deg); }
}
#keyframes spin2 {
to { transform: rotateY(360deg); }
}
.spin {
animation-name: spin1;
animation-duration: 2s;
}
.alt {
animation-name: spin2;
}
div {
width: 100px;
background: #8CF;
padding: 5px;
}
<div id=_square class=spin>
<button onclick="restart_animation(_square)">
Click to restart animation
</button>
</div>
On this page you can read about restarting the element animation: Restart CSS Animation (CSS Tricks)
Here is my example:
<head>
<style>
#keyframes selectss
{
0%{opacity: 0.7;transform:scale(1);}
100%{transform:scale(2);opacity: 0;}
}
</style>
<script>
function animation()
{
var elm = document.getElementById('circle');
elm.style.animation='selectss 2s ease-out';
var newone = elm.cloneNode(true);
elm.parentNode.replaceChild(newone, elm);
}
</script>
</head>
<body>
<div id="circle" style="height: 280px;width: 280px;opacity: 0;background-color: aqua;border-radius: 500px;"></div>
<button onclick="animation()"></button>
</body>
But if you want to you can just remove the element animation and then return it:
function animation()
{
var elm = document.getElementById('circle');
elm.style.animation='';
setTimeout(function () {elm.style.animation='selectss 2s ease-out';},10)
}
setInterval(() => {
$('#XMLID_640_').css('animation', 'none')
setTimeout(() => {
$('#XMLID_640_').css('animation', '')
}, 3000)
}, 13000)
Create a second "keyframe#" which restarts you animation, only problem with this you cannot set any animation properties for the restarting animation (it just kinda pops back)
HTML
<div class="slide">
Some text..............
<div id="slide-anim"></div>
</div><br>
<button onclick="slider()"> Animation </button>
<button id="anim-restart"> Restart Animation </button>
<script>
var animElement = document.getElementById('slide-anim');
document.getElementById('anim-restart').addEventListener("mouseup", restart_slider);
function slider() {
animElement.style.animationName = "slider"; // other animation properties are specified in CSS
}
function restart_slider() {
animElement.style.animation = "slider-restart";
}
</script>
CSS
.slide {
position: relative;
border: 3px black inset;
padding: 3px;
width: auto;
overflow: hidden;
}
.slide div:first-child {
position: absolute;
width: 100%;
height: 100%;
background: url(wood.jpg) repeat-x;
left: 0%;
top: 0%;
animation-duration: 2s;
animation-delay: 250ms;
animation-fill-mode: forwards;
animation-timing-function: cubic-bezier(.33,.99,1,1);
}
#keyframes slider {
to {left: 100%;}
}
#keyframes slider-restart {
to {left: 0%;}
}
Note that with React, clearing the animation like this, a codesandbox I found helps.
Example I used in my code:
function MyComponent() {
const [shouldTransition, setShouldTransition] = useState(true);
useEffect(() => {
setTimeout(() => {
// in my code, I change a background image here, and call this hook restart then animation,
// which first clears the animationName
setShouldTransition(false);
}, timeout * 1000);
}, [curr]);
useEffect(() => {
// then restore the animation name after it was cleared
if (shouldTransition === false) {
setShouldTransition(true);
}
}, [shouldTransition]);
return (
<div
ref={ref2}
style={{
animationName: shouldTransition ? "zoomin" : "",
}}
/>
);
}
I found out a simple solution today. Using the example provided in this answer, you can just append the element again to the body:
function resetAnimation() {
let element = document.getElementById('animated');
document.body.append(element);
}
#animated {
position: absolute;
width: 50px;
height: 50px;
background-color: LightSalmon;
animation: bounce 3s ease-in-out infinite;
}
#keyframes bounce {
0% {left: 0;}
50% {left: calc(100% - 50px);}
100% {left: 0;}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="animated"></div>
<button onclick="resetAnimation()">Reset</button>
</body>
</html>
Using Chrome's developer tools, the append does not actually append the element to the body and just replace it, probably because the same reference to the element is used.

Javascript / CSS animation is only played once [duplicate]

I have a CSS3 animation that needs to be restarted on a click. It's a bar showing how much time is left. I'm using the scaleY(0) transform to create the effect.
Now I need to restart the animation by restoring the bar to scaleY(1) and let it go to scaleY(0) again.
My first attempt to set scaleY(1) failed because it takes the same 15 seconds to bring it back to full length. Even if I change the duration to 0.1 second, I would need to delay or chain the assignment of scaleY(0) to let the bar replenishment complete.
It feels too complicated for such a simple task.
I also found an interesting tip to restart the animation by removing the element from the document, and then re-inserting a clone of it:
http://css-tricks.com/restart-css-animation/
It works, but is there a better way to restart a CSS animation?
I'm using Prototype and Move.js, but I'm not restricted to them.
No need in timeout, use reflow to apply the change:
function reset_animation() {
var el = document.getElementById('animated');
el.style.animation = 'none';
el.offsetHeight; /* trigger reflow */
el.style.animation = null;
}
#animated {
position: absolute;
width: 50px; height: 50px;
background-color: black;
animation: bounce 3s ease-in-out infinite;
}
#keyframes bounce {
0% { left: 0; }
50% { left: calc( 100% - 50px ); }
100% { left: 0; }
}
<div id="animated"></div>
<button onclick="reset_animation()">Reset</button>
Just set the animation property via JavaScript to "none" and then set a timeout that changes the property to "", so it inherits from the CSS again.
Demo for Webkit here: http://jsfiddle.net/leaverou/xK6sa/
However, keep in mind that in real world usage, you should also include -moz- (at least).
#ZachB's answer about the Web Animation API seems like "right"™ way to do this, but unfortunately seems to require that you define your animations through JavaScript. However it caught my eye and I found something related that's useful:
Element.getAnimations() and Document.getAnimations()
The support for them is pretty good as of 2021.
In my case, I wanted to restart all the animations on the page at the same time, so all I had to do was this:
const replayAnimations = () => {
document.getAnimations().forEach((anim) => {
anim.cancel();
anim.play();
});
};
But in most cases people will probably want to select which animation they restart...
getAnimations returns a bunch of CSSAnimation and CSSTransition objects that look like this:
animationName: "fade"
currentTime: 1500
effect: KeyframeEffect
composite: "replace"
pseudoElement: null
target: path.line.yellow
finished: Promise {<fulfilled>: CSSAnimation}
playState: "finished"
ready: Promise {<fulfilled>: CSSAnimation}
replaceState: "active"
timeline: DocumentTimeline {currentTime: 135640.502}
# ...etc
So you could use the animationName and target properties to select just the animations you want (albeit a little circuitously).
EDIT
Here's a handy function that might be more compatible using just Document.getAnimations, with TypeScript thrown in for demonstration/fun:
// restart animations on a given dom element
const restartAnimations = (element: Element): void => {
for (const animation of document.getAnimations()) {
if (element.contains((animation.effect as KeyframeEffect).target)) {
animation.cancel();
animation.play();
}
}
};
Implement the animation as a CSS descriptor
Add the descriptor to an element to start the animation
Use a animationend event handler function to remove the descriptor when the animation completes so that it will be ready to be added again next time you want to restart the animation.
HTML
<div id="animatedText">
Animation happens here
</div>
<script>
function startanimation(element) {
element.classList.add("animateDescriptor");
element.addEventListener( "animationend", function() {
element.classList.remove("animateDescriptor");
} );
}
</script>
<button onclick="startanimation(
document.getElementById('animatedText') )">
Click to animate above text
</button>
CSS
#keyframes fadeinout {
from { color: #000000; }
25% {color: #0000FF; }
50% {color: #00FF00; }
75% {color: #FF0000; }
to { color : #000000; }
}
.animateDescriptor {
animation: fadeinout 1.0s;
}
Try it here: jsfiddle
If you have a class for CSS3 animation, for example .blink, then you can removeClass for some element and addClass for this element thought setTimeout with 1 millisecond by click.
$("#element").click(function(){
$(this).removeClass("blink");
setTimeout(function(){
$(this).addClass("blink);
},1 // it may be only 1 millisecond, but it's enough
});
You can also use display property, just set the display to none.
display:none;
and the change backs it to block (or any other property you want).
display:block;
using JavaScript.
and it will work amazingly.
The Animation API gives you full control over when and what to play, and is supported by all modern browsers (Safari 12.1+, Chrome 44+, Firefox 48+, Edge 79+) .
const effect = new KeyframeEffect(
el, // Element to animate
[ // Keyframes
{transform: "translateY(0%)"},
{transform: "translateY(100%)"}
],
{duration: 3000, direction: "alternate", easing: "linear"} // Keyframe settings
);
const animation = new Animation(effect, document.timeline);
animation.play();
Demo: https://jsfiddle.net/cstz9L8v/
References:
https://developer.mozilla.org/en-US/docs/Web/API/KeyframeEffect/KeyframeEffect
https://developer.mozilla.org/en-US/docs/Web/API/Animation
There is an answer on MDN, which is similar to the reflow approach:
<div class="box">
</div>
<div class="runButton">Click me to run the animation</div>
#keyframes colorchange {
0% { background: yellow }
100% { background: blue }
}
.box {
width: 100px;
height: 100px;
border: 1px solid black;
}
.changing {
animation: colorchange 2s;
}
function play() {
document.querySelector(".box").className = "box";
window.requestAnimationFrame(function(time) {
window.requestAnimationFrame(function(time) {
document.querySelector(".box").className = "box changing";
});
});
}
If you create two identical sets of keyframes, you can "restart" the animation by swapping between them:
function restart_animation(element) {
element.classList.toggle('alt')
}
#keyframes spin1 {
to { transform: rotateY(360deg); }
}
#keyframes spin2 {
to { transform: rotateY(360deg); }
}
.spin {
animation-name: spin1;
animation-duration: 2s;
}
.alt {
animation-name: spin2;
}
div {
width: 100px;
background: #8CF;
padding: 5px;
}
<div id=_square class=spin>
<button onclick="restart_animation(_square)">
Click to restart animation
</button>
</div>
On this page you can read about restarting the element animation: Restart CSS Animation (CSS Tricks)
Here is my example:
<head>
<style>
#keyframes selectss
{
0%{opacity: 0.7;transform:scale(1);}
100%{transform:scale(2);opacity: 0;}
}
</style>
<script>
function animation()
{
var elm = document.getElementById('circle');
elm.style.animation='selectss 2s ease-out';
var newone = elm.cloneNode(true);
elm.parentNode.replaceChild(newone, elm);
}
</script>
</head>
<body>
<div id="circle" style="height: 280px;width: 280px;opacity: 0;background-color: aqua;border-radius: 500px;"></div>
<button onclick="animation()"></button>
</body>
But if you want to you can just remove the element animation and then return it:
function animation()
{
var elm = document.getElementById('circle');
elm.style.animation='';
setTimeout(function () {elm.style.animation='selectss 2s ease-out';},10)
}
setInterval(() => {
$('#XMLID_640_').css('animation', 'none')
setTimeout(() => {
$('#XMLID_640_').css('animation', '')
}, 3000)
}, 13000)
Create a second "keyframe#" which restarts you animation, only problem with this you cannot set any animation properties for the restarting animation (it just kinda pops back)
HTML
<div class="slide">
Some text..............
<div id="slide-anim"></div>
</div><br>
<button onclick="slider()"> Animation </button>
<button id="anim-restart"> Restart Animation </button>
<script>
var animElement = document.getElementById('slide-anim');
document.getElementById('anim-restart').addEventListener("mouseup", restart_slider);
function slider() {
animElement.style.animationName = "slider"; // other animation properties are specified in CSS
}
function restart_slider() {
animElement.style.animation = "slider-restart";
}
</script>
CSS
.slide {
position: relative;
border: 3px black inset;
padding: 3px;
width: auto;
overflow: hidden;
}
.slide div:first-child {
position: absolute;
width: 100%;
height: 100%;
background: url(wood.jpg) repeat-x;
left: 0%;
top: 0%;
animation-duration: 2s;
animation-delay: 250ms;
animation-fill-mode: forwards;
animation-timing-function: cubic-bezier(.33,.99,1,1);
}
#keyframes slider {
to {left: 100%;}
}
#keyframes slider-restart {
to {left: 0%;}
}
Note that with React, clearing the animation like this, a codesandbox I found helps.
Example I used in my code:
function MyComponent() {
const [shouldTransition, setShouldTransition] = useState(true);
useEffect(() => {
setTimeout(() => {
// in my code, I change a background image here, and call this hook restart then animation,
// which first clears the animationName
setShouldTransition(false);
}, timeout * 1000);
}, [curr]);
useEffect(() => {
// then restore the animation name after it was cleared
if (shouldTransition === false) {
setShouldTransition(true);
}
}, [shouldTransition]);
return (
<div
ref={ref2}
style={{
animationName: shouldTransition ? "zoomin" : "",
}}
/>
);
}
I found out a simple solution today. Using the example provided in this answer, you can just append the element again to the body:
function resetAnimation() {
let element = document.getElementById('animated');
document.body.append(element);
}
#animated {
position: absolute;
width: 50px;
height: 50px;
background-color: LightSalmon;
animation: bounce 3s ease-in-out infinite;
}
#keyframes bounce {
0% {left: 0;}
50% {left: calc(100% - 50px);}
100% {left: 0;}
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<div id="animated"></div>
<button onclick="resetAnimation()">Reset</button>
</body>
</html>
Using Chrome's developer tools, the append does not actually append the element to the body and just replace it, probably because the same reference to the element is used.

How do I get multiple css animations to play in javascript?

I'm a bit confused about how to trigger multiple animations for an element using javascript.
I'm trying to get an element (.hud) to fade-in and also bounce when clicked. Currently it will only do one or the other. The second animation class is being added to the element in a on click event. The class gets added but the animation does not play. How would I construct my code for the animation to fade-in and also bounce on click?
<!DOCTYPE html>
<html>
<head>
<style>
.anim {
animation-name: bounceIn_1;
animation-duration: .5s;
}
.hud {
width: 100px;
height: 100px;
background-color: red;
animation-name: fade-in;
animation-duration: .5s;
}
#-webkit-keyframes fade-in {
0% {
opacity: 0; }
100% {
opacity: 1; } }
#-webkit-keyframes bounceIn_1{0%,20%,40%,60%,80%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}20%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}40%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}60%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}80%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}to{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}}
</style>
</head>
<body>
<p>This box should fade in and bounce on click</p>
<div class="hud"></div>
<script>
element = document.querySelector('.hud');
console.log(element);
// reset the transition by...
element.addEventListener("click", function(e) {
console.log("clicked");
e.preventDefault;
element.classList.remove("anim");
void element.offsetWidth;
element.classList.add("anim");
}, false);
</script>
</body>
</html>
Was it so necessary for you? In order for the animation in your example to work constantly, a reset function is needed.
element = document.querySelector('#red_box');
console.log(element);
element.addEventListener("click", function(e) {
e.preventDefault;
console.log("clicked");
element.classList.remove("hud");
element.classList.remove("anim");
void element.offsetWidth;
element.classList.add("anim");
}, false);
/*$(".hud").click(function () {
var $this = $(this);
$this = reset($this);
$this.addClass("anim bounceIn_1");
console.log("clicked");
});*/
.anim {
width: 100px;
height: 100px;
background-color: red;
animation-name: bounceIn_1;
animation-duration: .5s;
}
.hud {
width: 100px;
height: 100px;
background-color: red;
animation-name: fade-in;
animation-duration: .5s;
}
#-webkit-keyframes fade-in {
0% {
opacity: 0; }
100% {
opacity: 1; } }
#-webkit-keyframes bounceIn_1 {0%,20%,40%,60%,80%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}20%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}40%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}60%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}80%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}to{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<body>
<p>This box should fade in and bounce on click</p>
<div id="red_box" class="hud"></div>
</body>
Have you tried to put a comma in your .anim class?
animation: bounceIn_1 .5s, fade-in .5s
You need to put the 2 animation in the same css class and make sure that the removing and the adding of that class are done in 2 separate frames.
The first issue can be easily solved by putting a comma between the 2 animations which are now in the class .anim.
The second issue is a little bit tricky but the window.requestAnimationFrame() function will solve it !
Here you have the modified code so that you can better understand:
element = document.querySelector('.hud');
console.log(element);
// reset the transition by...
element.addEventListener("click", function(e) {
console.log("clicked");
e.preventDefault;
element.classList.remove("anim");
void element.offsetWidth;
window.requestAnimationFrame(() => element.classList.add("anim")); /* The add() will be done before the next repaint so that we can see the change */
}, false);
.anim {
animation-name: fade-in, bounceIn_1;
animation-duration: .5s;
}
.hud {
width: 100px;
height: 100px;
background-color: red;
//animation-name: fade-in; /* Remove this */
//animation-duration: .5s; /* Remove this */
}
#-webkit-keyframes fade-in {
0% {
opacity: 0; }
100% {
opacity: 1; } }
#-webkit-keyframes bounceIn_1{0%,20%,40%,60%,80%,to{-webkit-animation-timing-function:cubic-bezier(.215,.61,.355,1);animation-timing-function:cubic-bezier(.215,.61,.355,1)}0%{opacity:0;-webkit-transform:scale3d(.3,.3,.3);transform:scale3d(.3,.3,.3)}20%{-webkit-transform:scale3d(1.1,1.1,1.1);transform:scale3d(1.1,1.1,1.1)}40%{-webkit-transform:scale3d(.9,.9,.9);transform:scale3d(.9,.9,.9)}60%{opacity:1;-webkit-transform:scale3d(1.03,1.03,1.03);transform:scale3d(1.03,1.03,1.03)}80%{-webkit-transform:scale3d(.97,.97,.97);transform:scale3d(.97,.97,.97)}to{opacity:1;-webkit-transform:scaleX(1);transform:scaleX(1)}}
<body>
<p>This box should fade in and bounce on click</p>
<div class="hud"></div>
</body>
Quick tip: with this method you can play as many animation as you want on the same element, just add its name to the .anim animations list and you're done!

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>

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>

Categories

Resources