Looping javascript function - javascript

I have a script that creates a progress bar and is style with CSS. It works great, but once the bar reaches the end, it stops and I can not get the script to loop so that it starts again. How can I loop this script so that the progress bar starts over once it reaches the end?
<script type="text/javascript">
$(document).ready(function() {
var el = $(''#progress'');
el.animate({
width: "100%"
}, 40000);
});
</script>
<style>
#progressKeeper {background:#f2f2f2;display:none;width: 400px;height: 18px;border: 1px solid #CCC;-moz-border-radius:7px; border-radius:7px;color:#f2f2f2;font-family:Arial;font- weight:bold;font-style:italic;font-size:.9em;margin-bottom:2000px;}
#progress {background: #005c9e;width: 0;height: 17px;-moz-border-radius:7px; border- radius:7px;}
</style>

Drop the jQuery, use CSS3!
#progress {
animation:progress 40s linear infinite;
-webkit-animation:progress 40s linear infinite;
}
#keyframes progress {from {width:0} to {width:100%}}
#-webkit-keyframes progress {from {width:0} to {width:100%}}
If you must support outdated browsers... well, pass a callback to the animate function to tell it to start the animation again. Something like this:
$(function() {
var prog = $("#progress");
anim();
function anim() {
prog.css({width:0});
prog.animate({width:"100%"},40000,anim);
}
});

Make it a function and pass that function to your .animate call as completion handler. See jQuery().animate().
Something like:
$(document).ready(function() {
function animateProgressBar( ) {
$('#progress').width(0).animate({
width : "100%"
}, 40000, animateProgressBar);
}
animateProgressBar();
});
(Untested)

Related

How to add function/element action after animate function runs in javascript?

I have tried searching on SO and google and cant seem to find a decent answer on this question.
I want to remove the element that is being animated after the animation is complete. After the single iteration, it puts the element back where it started. It seems to understand when the animation ends, where to add that last bit?
The code:
svg.animate([
// keyframes
{ transform: 'scale(2.5)'},
{ left: '50px',top:'175px',transform: 'scale(1.0)' }
], {
// timing options
duration: 600,
iterations: 1,
easing:'cubic-bezier(0.89, 0.41, 1, 0.95)'
})
What I want to add:
svg.remove()
Any ideas? thanks!
Use a promise:
Promise.all(
svg.getAnimations().map(
function(animation) {
return animation.finished
}
)
).then(
function() {
return svg.remove()
}
)
Look into animation events
Example:
HTML:
<button>Hello</button>
CSS:
#keyframes example {
from {background-color: red;}
to {background-color: yellow;}
}
button {
background-color: red;
animation-name: example;
animation-duration: 2s;
}
JS:
const button = document.querySelector("button");
button.addEventListener("animationend", () => { button.remove(); });
demo

Why animation play state is always running?

I couldn't get the animation play state to be paused with css3 animation even after using animation-iteration-count to 1 and animation-fill-mode to forwards:
var isRunning = window.getComputedStyle(
document.querySelector('div')
).getPropertyValue('animation-play-state');
setInterval(function(){
console.log(isRunning);
},1000)
#keyframes foo {
0% {
width: 0;
}
100% {
width: 50%;
}
}
div {
animation: foo 2s linear 0s 1 normal forwards;
background-color: #f00;
height: 3px;
}
<div></div>
I should get animation-play-state to be paused when it finishes the animation.
Actually, the following answer that I provided doesn't work for me. In fact, I was working with a pseudo element and pseudo element doesn't accept addEventListener. So, my final solution would be to use this only way.
var isRunning = window.getComputedStyle(
document.querySelector('div'), ':after'
).getPropertyValue('animation-play-state');
Sadly, CSS doesn't seem to set play state to paused when animation is finished. To conclude this question has no findings or solution?
The value of animation-play-state doesn't change once an animation finishes all its iterations.
You'll need to listen for the animationend event and change the value manually:
document.querySelector('div').addEventListener('animationend', function() {
this.style.animationPlayState = 'paused';
console.log(window.getComputedStyle(this).getPropertyValue('animation-play-state'));
});
#keyframes foo {
0% {
width: 0;
}
100% {
width: 50%;
}
}
#foo {
animation: foo 2s linear 0s 1 normal forwards;
background-color: #f00;
height: 3px;
}
<div id=foo></div>
... though I don't really see any reason to do so when your animation-fill-mode is already set to forwards.
I don't know why css3 keeps animation play state to running but go with the animationend event:
var x = document.getElementById("myDIV");
x.addEventListener("animationend", function(){
console.log('paused'); // animation is end
});
Here's the reference for animationend: https://developer.mozilla.org/en-US/docs/Web/Events/animationend

Triggering a JQuery animate function & looping it?

What I'm trying to do is (presumably) relatively simple, but let down by my (admittedly poor) understanding of jquery/Javascript.
The goal is simple - I want to 'animate' the opacity of a background image on a particular div (eventually I will apply this to others on the page, with the animation started/stopped according to the section being viewed - it's a horizontally scrolled page split into 'panels' the the viewer navigates with < & > buttons or named links).
Here's the script I've got so far (separate .js file, referenced in index.html);
jQuery(document).ready(function($) {
"use strict";
function animateSec1BG() {
$('#section1').animate({
opacity: 0,
}, 1000, function () {
$("#section1").css({ 'background-image': 'url(images/SlideBG-1.jpg)' }).animate({ opacity: 1 }, 1000);
});
}
});
No errors are reported for that (Dreamweaver CC, code view). At the bottom of index.html, after all scripts are loaded, I have this;
<script type="text/javascript">
$("#section1").animateSec1BG();
</script>
(the "#section1" bit I don't think is needed - code just didn't 'look' right without it - but doesn't work either way!).
Error returned states:
TypeError: $(...).animateSec1BG is not a function
I'm totally lost and somewhat out of my depth here, so any pointers much appreciated!
The function is defined within jQuery scope not global. Add the function to jQuery like:
jQuery.fn.animateSec1BG = function() {
$('#section1').animate({
opacity: 0,
}, 1000, function() {
$("#section1").css({
'background-image': 'url(images/SlideBG-1.jpg)'
}).animate({
opacity: 1
}, 1000);
});
}
Since the selector is hard coded, you can just define the function global one, and execute it when ROM is ready.
function animateSec1BG() {
// code
}
And call it animateSec1BG(). As for the loop, you can call the function within a interval using setInterval()
setInterval(animateSec1BG, 1000);
Another solution with CSS animation;
(This animation change the back-color. If you want, replace the background-color element with background-image element)
$.fn.animateSec1BG = function (state){
if(state)
$('#section1').addClass("sample");
else
$('#section1').removeClass("sample");
};
$(document).ready(function() { $("#section1").animateSec1BG(true); });
.sample {
width:100px;
height:20px;
background:red;
animation:myfirst 1s;
-moz-animation:myfirst 1s infinite; /* Firefox */
-webkit-animation:myfirst 1s infinite; /* Safari and Chrome */
}
#-moz-keyframes myfirst /* Firefox */
{
0% {background:red;}
50% {background:yellow;}
100% {background:red;}
}
#-webkit-keyframes myfirst /* Safari and Chrome */
{
0% {background:red;}
50% {background:yellow;}
100% {background:red;}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<section id="section1">
Some info and etc.
</section>

How do I add a pause in JavaScript?

I have a div like this:
<div style="width: 0%;"></div>
How can I change the css of width to 100% (and wait until it reaches 100%) before changing more elements?
For example:
$('div').css('width', '100%', function() {
$('div').css('color', 'red');
});
Obviously this doesn't work, but how can I make it work?
You can just use a timer to wait before processing some more code:
$('div').css('width', '100%');
setTimeout(function(){
$('div').css('color','red');
}, 2000);
JSFiddle
Use jQuery animate()
$("div").animate({
width:"100%"
}, 2000, function() {
//On Animation complete
$('div').css('color', 'red');
});
Fiddle
You can do it a number of ways. One way is to use CSS transitions:
.yourDiv {
width: 0%;
-webkit-transition: width;
-webkit-transition-duration: 3s;
background: yellow;
}
.yourDiv.wide {
width: 100%;
}
Then, to animate, apply the class via jQuery:
$('.yourDiv').addClass('wide')
To do something after it's done animating, use the webkitTransitionEnd event:
$('.yourDiv')
.addClass('wide')
.one('webkitTransitionEnd', function(){
$('this').css('background','red')
})
If you wan to wait for a period of time after the animation finished before triggering your next style change, wrap it in a setTimeout:
var $yourDiv = $('.yourDiv')
$yourDiv
.addClass('wide')
.one('webkitTransitionEnd', function(){
setTimeout(function(){
$yourDiv.css('background','red')
},2000)
})
fiddle: http://jsfiddle.net/22fPQ/1/
(note the above is webkit-centric. Use other browser CSS prefixes as needed to support)

How to pause a css animation, and then continue running from the pause point?

I'm playing a CSS animation with infinite iterations, until some point I pausing it from java script (using technique from here).
At later time I resume the animation. The problem is that the animation is restarting from the beginning point, and not from the last point before the pause.
Does there is a way to continue the animation from the pause point, without jumping to the start?
Edit: Between the pause and resume I also change the animation duration, see the demo.
You should see some 'jumping'. Need explanation about this strange behavior.
http://jsfiddle.net/zhang6464/MSqMQ/
Just switch animation-play-state css property to be paused, according to the article you supplied(http://css-tricks.com/restart-css-animation/
I've just started to dig into JS myself, so there are surely better ways to do this, but how about something like this - Demo (Unprefixed version).
CSS
#box {
position: relative;
top: 20px;
left: 20px;
width: 100px;
height: 100px;
background: #393939;
animation: move 2s linear infinite;
animation-play-state: running;
}
#keyframes move {
100% {
transform: rotate(360deg);
}
}
JS:
(function () {
var box = document.getElementById('box');
box.onclick = function () {
if (box.style.animationPlayState === "paused") {
box.style.animationPlayState = "running";
} else {
box.style.animationPlayState = "paused";
}
};
})();
Based on if the animation is running or paused I change the animation-play-state onclick.
EDIT: Added the css code.

Categories