I am trying to make a div slide to the left and THEN disappear. I am using this code.
function slide_in(current_my) {
$("#" + current_my).animate({
left: "510"
}, {
duration: 750
});
document.getElementById(current_my).style.display = "none";
}
if I remove the last line of code the div slides nicely to the left over 750ms. But when I add the last line the div just disappears.
I tired adding:
wait(750);
before the last line, where the 'wait' function was defined as :
function wait(ms)
{
var d = new Date();
var d2 = null;
do { d2 = new Date(); }
while(d2-d < ms);
}
but that just made the div sit there for 750ms and then disappear. Again, what I want is for the 'current_my' div to slide / animate and THEN disappear (display:none). Any ideas? Thank you.
You need to use the complete option of jQuery animate. Also since you already have the object, there is no point in going to find it again. In your complete method, you can just use the this keyword and apply the hiding or any other animation directly to the object again.
$("#" + current_my).animate({ left: "510" }, { duration: 750 }, function() {
$(this).hide();
});
You should hide the div in complete callback
function slide_in(current_my) {
$("#" + current_my).animate({
left: "510"
}, 750, function() {
document.getElementById(current_my).style.display = "none";
});
}
Doc reference
Animate takes a callback when finished.
You could
function slide_in(current_my) {
$("#" + current_my).animate({
left: "510"
}, {
duration: 750
}, function () {
document.getElementById(current_my).style.display = "none";
});
}
An alternative using animate.css, you would need to adjust the animation duration on the css file.
$(document).ready(function() {
$('button.btn').click(function() {
$('div.box').addClass('animated fadeOutLeftBig');
});
});
.box {
width: 50px;
height: 50px;
margin-left: 200px;
background-color: red;
}
.box p {
text-align: center;
font-size: 1em;
}
div.box {
-webkit-animation-duration: 5s;
-webkit-animation-delay: 0s;
-moz-animation-duration: 5s;
-moz-animation-delay: 0s;
-ms-animation-duration: 5s;
-ms-animation-delay: 0s;
}
<link href="https://cdnjs.cloudflare.com/ajax/libs/animate.css/3.5.2/animate.min.css" rel="stylesheet"/>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="box">
<p>Test</p>
</div>
<button class="btn">Fade Left</button>
This is slightly more than asked but lets make it fun. Toss in an event to trigger the animation instead of a function, passing the location and duration numbers just for fun:
$(document).on('slidehide', '.myanimate', function(event, requstedduration, whereto, shouldhide) {
var p = $(this).position();
$(this).animate({
left: whereto
}, {
duration: requstedduration,
start: function() {$('.silly').toggle(shouldhide);},
complete: function() {
$(this).toggle(!shouldhide);
}
});
});
$('.myanimate').on('click', function() {
console.log('moving');
$(this).trigger('slidehide', [750, 510, true]);
});
// just so we can restart/see again
$(document).on('click', '.silly', function() {
console.log('restart');
$('.myanimate').show().trigger('slidehide', [750, 10, false]);;
});
.myanimate {
position: absolute;
left: 100px;
}
.silly {
display: none;
)
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<div class="myanimate">howdy there (click to trigger)</div>
<div class='silly'>Animation complete. (click to restart)</div>
Related
I made a small animation
When clicked, the animated square will change its height, but it will also animate when the window size / scale is changed. How to make it animate only when clicked, and in other cases just resize (no animation)
function myClick() {
document.getElementById("myDiv").style.height = Math.floor(Math.random() * 100) + "vmin";
}
#myDiv {
width: 20vmin;
height: 20vmin;
background: green;
transition: height 1s ease;
}
#myDiv:active {
background: blue;
}
<!DOCTYPE html>
<body>
<div id="myDiv" onclick="myClick()"></div>
</body>
</html>
One method is to add a class with transition and remove it after animation finished:
var timer;
document.getElementById("myDiv").addEventListener("transitionend", function(e)
{
clearTimeout(timer);
document.getElementById("myDiv").classList.toggle("clicked", false);
}, false);
function myClick() {
clearTimeout(timer);
document.getElementById("myDiv").classList.toggle("clicked", true);
document.getElementById("myDiv").style.height = Math.floor(Math.random() * 100) + "vmin";
timer = setTimeout(function() { //backup plan
document.getElementById("myDiv").classList.toggle("clicked", false);
}, 2000);
}
#myDiv {
width: 20vmin;
height: 20vmin;
background: green;
}
#myDiv:active {
background: blue;
}
#myDiv.clicked {
transition: height 1s ease;
}
<body>
<div id="myDiv" onclick="myClick()"></div>
</body>
Another method is to remove transition class when window is resized
function myClick() {
document.getElementById("myDiv").classList.toggle("clicked", true);
document.getElementById("myDiv").style.height = Math.floor(Math.random() * 100) + "vmin";
}
window.addEventListener('resize', function() {
document.getElementById("myDiv").classList.toggle("clicked", false);
});
#myDiv {
width: 20vmin;
height: 20vmin;
background: green;
}
#myDiv:active {
background: blue;
}
#myDiv.clicked {
transition: height 1s ease;
}
<body>
<div id="myDiv" onclick="myClick()"></div>
</body>
The only way I know is the listening window resize event.
We are removing the transition effect while resizing in here;
const myDiv = document.getElementById("myDiv")
window.addEventListener('resize', () => {
myDiv.style.transition = "all 0s ease 0s"
});
But then you have to put the transition back when you click like this;
function myClick() {
if(myDiv.style.transition === "all 0s ease 0s"){
myDiv.style.transition = "height 1s ease";
}
myDiv.style.height = Math.floor(Math.random() * 100) + "vmin";
}
Here's one way. It's a bit crude but it works. The div only has an animate class while the animation is taking place, using a timer. I made the timer longer than necessary and it turns yellow to make clear what's happening. I'm not sure if it can be done without a timer kludge.
let animateTimeout;
function myClick() {
let myDiv = document.getElementById("myDiv");
myDiv.style.height = Math.floor(Math.random() * 100) + "vmin";
myDiv.classList.add("animate");
clearTimeout(animateTimeout);
animateTimeout = setTimeout(() => myDiv.classList.remove("animate"), 1500);
}
#myDiv {
width: 20vmin;
height: 20vmin;
background: green;
}
#myDiv.animate {
background: yellow;
transition: height 1s ease;
}
#myDiv:active {
background: blue;
}
<!DOCTYPE html>
<body>
<div id="myDiv" onclick="myClick()"></div>
</body>
</html>
I've got a simple empty HTML div:
<div id="spaceTrainingImages"></div>
I am adding images dynamically to it:
// adds the images to the img div
imgContainerSpace = $("#spaceTrainingImages");
for (var i = 1; i <= numStimuli; i++) {
imgContainerSpace.append(
$("<img>", {
id: "spaceTrainingImg" + i,
src: numToPath(i),
style: "width:30px;height:40px",
"class": "spaceTrainingPic"
})
);
};
Moreover, I change the dimension of each img as the mouse hovers over it.
// deals with size change on mouse over
$(".spaceTrainingPic").hover(function() {
// img gets three times bigger
$(this).css({
"width": "90px",
"height": "120px",
});
}, function() {
// img returns to original size
$(this).css({
"width": "30px",
"height": "40px",
});
});
I would like the imgs to be at the center of the div and remain there:
#spaceTrainingImages {
position: relative;
height: 120px;
background-color: snow;
}
.spaceTrainingPic {
position: relative;
top: 50%;
transform: translateY(-50%);
}
This works whenever the mouse is not hovering over any image. However, whenever I hover over an image, all the other images move. Their top becomes the bottom of the image being hovered (which becomes bigger).
I am not sure what might be causing this.
EDIT: I had forgotten to mention that I do want the imgs to move to the sides when the hovered over image gets bigger, I just don't want them to move vertically.
You can use transform scale() instead of changing height and width value.
As I see you are changing values 30 to 90 and 40 to 120 which is 3 times of original value so use transform: scale(3);
$(".spaceTrainingPic").hover(
function() {
// img gets three times bigger
$(this).css({
"transform": "scale(3) translateY(-50%)"
});
},
function() {
// img returns to original size
$(this).css({
"transform": "scale(1) translateY(-50%)"
});
});
$(document).ready(function() {
imgContainerSpace = $("#spaceTrainingImages");
for (var i = 1; i <= 5; i++) {
imgContainerSpace.append(
$("<img>", {
id: "spaceTrainingImg" + i,
src: 'https://www.jquery-az.com/html/images/banana.jpg',
style: "width:30px;height:40px",
"class": "spaceTrainingPic"
})
);
};
$(".spaceTrainingPic").hover(function() {
$(this).css({
"transform": "scale(3) translateY(-16.666667%)",
"z-index": "1"
});
$(this).next("img").css({
"margin-left": "30px",
});
}, function() {
$(this).css({
"transform": "scale(1) translateY(-50%)"
});
$(this).next("img").css({
"margin-left": "0px",
});
});
});
#spaceTrainingImages {
position: relative;
height: 120px;
background-color: snow;
}
.spaceTrainingPic {
position: relative;
top: 50%;
transform: translateY(-50%);
transition: all .3s ease;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spaceTrainingImages"></div>
this can be done quite simply without so much javascript and just pure css.
First when you foreach create div and inside append the image.
This div can have class img-wrapper with
.img-wrapper {
width: 30px;
height: 40px;
overflow:hidden;
}
.img-wrapper img {
width: 100%;
height: auto;
transition: all 0.3s linear;
}
.img-wrapper:hover img {
transform: scale(1.2);
}
So basically
You need something like this
<div id="spaceTrainingImages">
<div class="img-wrapper">
your img here
</div>
<div class="img-wrapper">
your img here
</div>
<div class="img-wrapper">
your img here
</div>
</div>
There is a transform property in CSS which helps to ZOOM the element content without disturbing the others. Take a look at below
$(document).ready(function() {
// adds the images to the img div
imgContainerSpace = $("#spaceTrainingImages");
for (var i = 1; i <= 5; i++) {
imgContainerSpace.append(
$("<img>", {
id: "spaceTrainingImg" + i,
src: 'https://www.jquery-az.com/html/images/banana.jpg',
style: "width:30px;height:40px",
"class": "spaceTrainingPic"
})
);
};
// deals with size change on mouse over
$(".spaceTrainingPic").hover(
function() {
// img gets three times bigger
$(this).css({
"transform": "scale(3)",
"z-index":"1"
});
},
function() {
// img returns to original size
$(this).css({
"transform": "scale(1)"
});
});
})
#spaceTrainingImages {
position: relative;
height: 120px;
background-color: snow;
}
.spaceTrainingPic {
position: relative;
top: 50%;
transform: translateY(-50%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="spaceTrainingImages"></div>
Hope this helps
I think you would be better of using the tranform css property.
$(".spaceTrainingPic").hover(
function () {
// img gets three times bigger
$(this).css({
"transform": "scale(3)"
});
}, function () {
// img returns to original size
$(this).css({
"transform": "scale(1)"
});
});
You could also do this with pure css
.spaceTrainingPic:hover {
transform: scale(3);
}
I want to have a fixed nav which fades out when the mouse isn't moving and fades back in when it does.
I've came across this other post which does the job but the problem is that it uses visibility and I want to use opacity that way I can make it fade in and out with a transition transition: all .4s ease-in-out;
$("#fp-nav").style.opacity = "0";
$("html").mousemove(function(event) {
$("#fp-nav").style.opacity = "1";
myStopFunction();
myFunction();
});
function myFunction() {
myVar = setTimeout(function() {
$("#fp-nav").style.opacity = "0";
}, 1000);
}
function myStopFunction() {
if (typeof myVar != 'undefined') {
clearTimeout(myVar);
}
}
#fp-nav {
position: fixed;
z-index: 100;
top: 50%;
opacity: 1;
-webkit-transform: translate3d(0, 0, 0);
transition: all .4s ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="fp-nav">
Hello world Hello world Hello world Hello world
</div>
Or am I supposed to use fp-nav.style.opacity = "0"; instead of $("#fp-nav").style.opacity = "0";
You can replace .hide() and .show() by your own css code to visually hide the bar: hide becomes css("opacity", 0) and show becomes css("opacity", 1).
Then, you add a transition to your bar:
.navbar {
transition: opacity 1000ms ease-in-out;
};
$("div").css("opacity", 0);
$("html").mousemove(function( event ) {
$("div").css("opacity", 1);
myStopFunction();
myFunction();
});
function myFunction() {
myVar = setTimeout(function(){
$("div").css("opacity", 0);
}, 1000);
}
function myStopFunction() {
if(typeof myVar != 'undefined'){
clearTimeout(myVar);
}
}
div {
transition: opacity 1000ms ease-in-out;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>navbar</div>
It might be nice to let the css define how you want to hide/show via an additional class. You can then, for example, use addClass("is-hidden") and removeClass("is-hidden"):
var hiddenClass = "is-hidden";
var customHide = function($el) {
$el.addClass(hiddenClass);
}
var customShow = function($el) {
$el.removeClass(hiddenClass);
}
customHide($("div"));
$("html").mousemove(function( event ) {
customShow($("div"));
myStopFunction();
myFunction();
});
function myFunction() {
myVar = setTimeout(function(){
customHide($("div"));
}, 1000);
}
function myStopFunction() {
if(typeof myVar != 'undefined'){
clearTimeout(myVar);
}
}
/* CSS now determines how we want to hide our bar */
div {
position: relative;
background: green;
transition: transform 500ms ease-in-out;
}
div.is-hidden {
transform: translateY(-160%);
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div>navbar</div>
$(document).on('mousemove', function(){
$('#nav').addClass('shown');
setTimeout(function(){
$('#nav').removeClass('shown');
}, 5000);
});
#nav {
opacity: 0;
transition: opacity 1s ease-in-out;
background: black;
width: 300px;
height: 100px;
}
#nav.shown {
opacity: 1;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="nav">
</div>
Here's my go:
Obviously, edit the timings and opacity as needed. The animations themselves are pure CSS, and JS is just used to add/remove a class from the nav.
I am trying to turn on and turn off a function on click - toggle a function.
I want .fly element to not disappear, only the animation should stop and return to its origin. When the button is clicked, the animation should stop. When it's clicked again, the animation starts again.
HTML
<div class="hobbie-box">
<div class="circle-image">
<i id="travel" class="fa fa-plane fly"></i>
</div>
<div class="circle-text">
<p>Travel industry</p>
</div>
</div>
<button type="button" class="btn toggle-effects">Turn off effects</button>
Javascript
var flyplane = function(){
setInterval(function() {
$fly.animate({
right: '-=50',
bottom: '+=50'
}, 2000, function() {
$fly.removeAttr("style");
});
}, 2000);
};
flyplane();
$(".toggle-effects").on("click", function () {
$(this).text(function (i, text) {
return text === "Turn off effects" ? "Turn on effects" : "Turn off effects";
})
$("#travel").toggle($fly);
}); //end of button click
There is a live example.
Please refer to my codepen
<div class="hobbie-box">
<div class="circle-image">
<i id="travel" class="fa fa-plane fly"></i>
</div>
<div class="circle-text">
<p>Travel industry</p>
</div>
</div>
<button class='toggle-effects'>[btn]</button>
#travel {
width: 50px;
height: 50px;
background-color: red;
display: block;
position: relative;
}
var $fly = $('.fly');
var flyplane = function() {
$fly.animate({
right: '-=50',
bottom: '+=50'
}, 2000, function() {
console.log('animation complete')
$fly.removeAttr("style");
flyplane();
});
};
//flyplane();
var count = 1;
$(".toggle-effects").on("click", function() {
console.log('click');
var isHidden = count++%2 !== 0;
if( isHidden ) {
$("#travel").show( 0, flyplane);
} else {
$("#travel").hide( 0 );
$fly.stop();
}
}); //end of button click
Not sure if that's what you are trying to achieve, but, if using setInterval:
You must save it into a variable, e.g variable = setInterval(function() { /* ... */ }, 2000);
To stop the interval, you must use clearInterval, e.g clearInterval(variable);.
And then, to star the interval again, you must call setInterval again, so it's better to encapsulate your code into a function, so you don't need to rewrite the same code twice.
Since, your flyplane function was already there, I only used it.
Take a look at the snippet below, and tell me if that's what you're trying to achive:
$(function() {
var $fly = $('.fly'), interval;
var flyplane = function() {
interval = setInterval(function() {
$fly.animate({
right: '-=50',
bottom: '+=50'
}, 2000, function() {
$fly.removeAttr("style");
});
}, 2000);
};
flyplane();
$(".toggle-effects").on("click", function() {
$(this).text(function(i, text) {
if (text === "Turn off effects") {
clearInterval(interval);
return "Turn on effects";
}
else {
flyplane();
return "Turn off effects";
}
})
}); //end of button click
});
.fly {
display: block;
width: 20px;
height: 20px;
background-color: yellow;
position: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hobbie-box">
<div class="circle-image">
<i id="travel" class="fa fa-plane fly"></i>
</div>
<div class="circle-text">
<p>Travel industry</p>
</div>
</div>
<button type="button" class="btn toggle-effects">Turn off effects</button>
Thanks for your answers. I decided to try the css approach for animation using http://www.w3schools.com/css/css3_animations.asp as a guide.
All I did was add the css animation:
i.fly {
-webkit-animation-name: flying;
-webkit-animation-duration: 4s;
-webkit-animation-iteration-count: infinite;
animation-name: flying;
animation-duration: 4s;
animation-iteration-count: infinite;
}
#-webkit-keyframes flying {
0% {
right: 0px;
bottom: 0px;
}
100% {
right: -50px;
bottom: 50px;
}
}
#keyframes flying {
0% {
right: 0px;
bottom: 0px;
}
100% {
right: -50px;
bottom: 50px;
}
}
on js:
$("#travel").toggleClass("fly");
Most important thing was to toggle the effect with the button
First of all if you need an event to be executed once after a delay you should use setTimeout() function nstead of setInterval().
And instead of using .animate in JavaScript you can simply add a class fly to your element using .toggleClass() function.
This is a working snippet:
var $fly = $('.fly');
var flyplane = function() {
setTimeout(function() {
$fly.toggleClass('fly');
}, 2000);
};
flyplane();
$(".toggle-effects").on("click", function() {
$("#travel").toggle(0, flyplane);
}); //end of button click
.fly{
right: -50
bottom: +50
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="hobbie-box">
<div class="circle-image">
<i id="travel" class="fa fa-plane"></i>
</div>
<div class="circle-text">
<p>Travel industry</p>
</div>
</div>
<input type="button" class="toggle-effects" value="click" />
You could just check for a var like this
$fly = $(".fly")
fly = true
flyplane = function(){
setInterval(function() {
if(fly){
$fly.animate({
right: '-=50',
bottom: '+=50'
}, 2000, function() {
$fly.removeAttr("style");
});
}
}, 2000);
};
$(".toggle-effects").on("click", function () {
fly = !fly
});
.fly{
width: 3px;
height: 3px;
position: absolute;
background-color: #00ff00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="fly"></div>
So, I've got this -webkit-animation rule:
#-webkit-keyframes shake {
0% {
left: 0;
}
25% {
left: 12px;
}
50% {
left: 0;
}
75% {
left: -12px;
}
100% {
left:0;
}
}
And some CSS defining some of the animation rules on my box:
#box{
-webkit-animation-duration: .02s;
-webkit-animation-iteration-count: 10;
-webkit-animation-timing-function: linear;
}
I can shake the #box like this:
document.getElementById("box").style.webkitAnimationName = "shake";
But I can't shake it again later.
This only shakes the box once:
someElem.onclick = function(){
document.getElementById("box").style.webkitAnimationName = "shake";
}
How can I re-trigger a CSS animation via JavaScript without using timeouts or multiple animations?
I found the answer based on the source code and examples at the CSS3 transition tests github page.
Basically, CSS animations have an animationEnd event that is fired when the animation completes.
For webkit browsers this event is named “webkitAnimationEnd”. So, in order to reset an animation after it has been called you need to add an event-listener to the element for the animationEnd event.
In plain vanilla javascript:
var element = document.getElementById('box');
element.addEventListener('webkitAnimationEnd', function(){
this.style.webkitAnimationName = '';
}, false);
document.getElementById('button').onclick = function(){
element.style.webkitAnimationName = 'shake';
// you'll probably want to preventDefault here.
};
and with jQuery:
var $element = $('#box').bind('webkitAnimationEnd', function(){
this.style.webkitAnimationName = '';
});
$('#button').click(function(){
$element.css('webkitAnimationName', 'shake');
// you'll probably want to preventDefault here.
});
The source code for CSS3 transition tests (mentioned above) has the following support object which may be helpful for cross-browser CSS transitions, transforms, and animations.
Here is the support code (re-formatted):
var css3AnimationSupport = (function(){
var div = document.createElement('div'),
divStyle = div.style,
// you'll probably be better off using a `switch` instead of theses ternary ops
support = {
transition:
divStyle.MozTransition === ''? {name: 'MozTransition' , end: 'transitionend'} :
// Will ms add a prefix to the transitionend event?
(divStyle.MsTransition === ''? {name: 'MsTransition' , end: 'msTransitionend'} :
(divStyle.WebkitTransition === ''? {name: 'WebkitTransition', end: 'webkitTransitionEnd'} :
(divStyle.OTransition === ''? {name: 'OTransition' , end: 'oTransitionEnd'} :
(divStyle.transition === ''? {name: 'transition' , end: 'transitionend'} :
false)))),
transform:
divStyle.MozTransform === '' ? 'MozTransform' :
(divStyle.MsTransform === '' ? 'MsTransform' :
(divStyle.WebkitTransform === '' ? 'WebkitTransform' :
(divStyle.OTransform === '' ? 'OTransform' :
(divStyle.transform === '' ? 'transform' :
false))))
//, animation: ...
};
support.transformProp = support.transform.name.replace(/([A-Z])/g, '-$1').toLowerCase();
return support;
}());
I have not added the code to detect “animation” properties for each browser. I’ve made this answer “community wiki” and leave that to you. :-)
You have to first remove the animation, then add it again. Eg:
document.getElementById("box").style.webkitAnimationName = "";
setTimeout(function ()
{
document.getElementById("box").style.webkitAnimationName = "shake";
}, 0);
To do this without setTimeout remove the animation during onmousedown, and add it during onclick:
someElem.onmousedown = function()
{
document.getElementById("box").style.webkitAnimationName = "";
}
someElem.onclick = function()
{
document.getElementById("box").style.webkitAnimationName = "shake";
}
Following the suggestion from https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Animations/Tips, remove and then add the animation class, using requestAnimationFrame to ensure that the rendering engine processes both changes. I think this is cleaner than using setTimeout, and handles replaying an animation before the previous play has completed.
$('#shake-the-box').click(function(){
$('#box').removeClass("trigger");
window.requestAnimationFrame(function(time) {
window.requestAnimationFrame(function(time) {
$('#box').addClass("trigger");
});
});
});
http://jsfiddle.net/gcmwyr14/5/
A simple but effective alternative:
HTML:
<div id="box"></div>
<button id="shake-the-box">Shake it!</button>
css:
#box{
background: blue;
margin:30px;
height:50px;
width:50px;
position:relative;
-moz-animation:shake .2s 0 linear 1;
-webkit-animation:shake .2s 0 linear 1;
}
#box.trigger{
display:table;
}
#-webkit-keyframes shake {
0% {
left: 0;
}
25% {
left: 12px;
}
50% {
left: 0;
}
75% {
left: -12px;
}
100% {
left:0;
}
}
#-moz-keyframes shake {
0% {
left: 0;
}
25% {
left: 12px;
}
50% {
left: 0;
}
75% {
left: -12px;
}
100% {
left:0;
}
}
jQuery:
$('#shake-the-box').click(function(){
$('#box').toggleClass('trigger');
});
Demo:
http://jsfiddle.net/5832R/2/
Issues:
I don't know if it works on Firefox, because the animation doesn't seem to work there...
Clone works pretty good on paused Karaoke:
On IE11 had to force a reflow (R. Krupiński's shorter version).
$('#lyrics').text("Why does it hurt when I pee?");
changeLyrics('3s');
function changeLyrics(sec) {
str = 'lyrics '+ sec + ' linear 1';
$('#lyrics').css( 'animation', str);
$('#lyrics').css( 'animation-play-state', 'running' );
$('#lyrics').replaceWith($('#lyrics').clone(true));
}
or you can use the following:
function resetAnimation(elm) {
$('#'+elm).replaceWith($('#'+elm).clone(true));
}
Reset the value first. Use reflow to apply the change without using timeout:
function shake() {
var box = document.getElementById("box");
box.style.animationName = null;
box.offsetHeight; /* trigger reflow */
box.style.animationName = "shake";
}
#keyframes shake {
0% { left: 0; }
25% { left: 12px; }
50% { left: 0; }
75% { left: -12px; }
100% { left: 0; }
}
#box {
position: absolute;
width: 75px; height: 75px;
background-color: black;
animation-duration: .02s;
animation-iteration-count: 10;
animation-timing-function: linear;
}
button {
position: absolute;
top: 100px;
}
<div id="box"></div>
<button onclick="shake()">Shake</button>
In contrast to the accepted answer that recommends animationEnd, this method resets the animation even when it's still in progress. This might be or might be not what you want.
An alternative would be to create a duplicate #keyframes animation and switch between the two:
function shake() {
var box = document.getElementById("box");
if (box.style.animationName === "shake")
box.style.animationName = "shake2";
else
box.style.animationName = "shake";
}
#keyframes shake {
0% { left: 0; }
25% { left: 12px; }
50% { left: 0; }
75% { left: -12px; }
100% { left: 0; }
}
#keyframes shake2 {
0% { left: 0; }
25% { left: 12px; }
50% { left: 0; }
75% { left: -12px; }
100% { left: 0; }
}
#box {
position: absolute;
width: 75px; height: 75px;
background-color: black;
animation-duration: .02s;
animation-iteration-count: 10;
animation-timing-function: linear;
}
button {
position: absolute;
top: 100px;
}
<div id="box"></div>
<button onclick="shake()">Shake</button>
Is there an issue with using setTimeout() to remove the class and then read it 5ms later?
svg.classList.remove('animate');
setTimeout(function() {
svg.classList.add('animate');
}, 10);
With your javascript, you could also add (and then remove) a CSS class in which the animation is declared. See what I mean ?
#cart p.anim {
animation: demo 1s 1; // Fire once the "demo" animation which last 1s
}
1) Add animation name to the #box.trigger in css
#box.trigger{
display:table;
animation:shake .2s 0 linear 1;
-moz-animation:shake .2s 0 linear 1;
-webkit-animation:shake .2s 0 linear 1;
}
2) In java-script you cannot remove the class trigger.
3) Remove the the class name by using setTimeOut method.
$(document).ready(function(){
$('#shake-the-box').click(function(){
$('#box').addClass('trigger');
setTimeout(function(){
$("#box").removeClass("trigger")},500)
});
});
4) Here is the DEMO.