jQuery cancel previously queued event handlers to restart CSS animation - javascript

I'm creating a slideshow, which will run on a timer (shown by progress bar), but allow users to click arrows to force next. I'm trying to use as much CSS3 as possible, so for my loop timer I'm using the CSS3 animation of the progress bar.
The way it works is that I start my progress bar at width:0, and set it to width:100%;. It has a CSS3 transition of 5s. I then watch for the end of the animation, and use that to call my resetprogress and changeimage functions, after which I then start the progress again. It loops indefinitely.
I've created a jsFiddle, simplified, to show what I'm talking about: http://jsfiddle.net/a3H9L/
Code for the simplified version is below. As you can see, I call startProgress, in which I start the CSS3 animation by changing the width, then set a watcher for the end of said animation, at which point I reset and then start again.
startProgress();
function startProgress() {
$('div').width('100%');
$('div').one('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend',function(e){
resetProgress();
startProgress();
});
}
function resetProgress (){
$('div').addClass('notransition'); // Disable transitions
$('div').width('0');
$('div')[0].offsetHeight; // Trigger a reflow, flushing the CSS changes
$('div').removeClass('notransition'); // Re-enable transitions
}
$('button').click(function(event){
resetProgress();
startProgress();
});
My question is, if a user clicks the reset (which will eventually be Next and Previous), how do I break the original loop before resetting and starting a new loop? Right now, I think that I'm starting a new loop without ending the original, which is getting me two loops running at the same time.
EDIT: The reason I think something is wrong is that as I clicked reset a few times, things in the loop start happening at other times besides when the progress is reset.

TL;DR:
Simply call an .off() before chaining your .one()
Let's run an experiment using your fiddle.
Experiment 1:
Using the console to log a simple message everytime the .one() function is called:
$('div').one('...', function(e) {
console.log('one called!');
resetProgress();
startProgress();
});
Observation:
Yes, you are right, they do stack! If you click on the button, more .one() functions are added and will fire together at the same time once the bar reaches the end of the animation. ALL of them will still fire once the animation completes the following and subsequent times!
i.e.: Run fiddle, click your button five times. On completion of the first animation, console logs six messages (5 + 1). The bar resets itself and produces another six more messages. This goes on in multiples of six.
Experiment 2:
Now, let's try turning itself off at the start of the function:
$('div').one('...', function(e) {
$(this).off(e);
console.log('one called!');
resetProgress();
startProgress();
});
Observation:
This didn't produce the cancelling effect we were expecting. Same result as the first experiment.
Experiment 3:
Let's try turning all the handlers off (by omitting the "e"):
$('div').one('...', function(e) {
$(this).off();
console.log('one called!');
resetProgress();
startProgress();
});
Observation:
All queued .one() handlers execute at the end of the animation, but they terminate themselves after running once and do not fire the next time the animation completes.
Experiment 4:
What you actually wanted to do, was to cancel all previously queued handlers before setting a new one. So let's do this:
$('div').off().one('...', function(e) {
console.log('one called!');
resetProgress();
startProgress();
});
Observation:
There's your answer! This function now runs once, as the previous handlers were unset before a new one has been placed. Simply call an .off() before chaining your .one()
Disclaimer:
These experiments assume that those were your only event handlers on your element. If you have additional handlers set by .on(), .one() or similar, instead of using .off() to clear everything, you have to specify which handlers you want to clear, like so:
.off('webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend')

Related

How can I write a function(a) which calls another function(b) when it completes?

I have a list of inputs(type="radio") and I'm running a animation when they're clicked, also I'm disabling the inputs whilst the animation is running.
How can I get this function to call another when its finished running?
function animation(para1, para2, para3, para4) {
// calling a function to clear the animation for time before
// this gets called when a input is clicked to run a animation
// also hides inputs
}
I need to somehow call another function to re-enable the inputs once the animation is complete
Either use callbacks, which are just function parameters and have been around for quite some time, like so
function animation(para1, para2, para3, para4, callbackFn) {
//do the work
callbackFn(); //work is done, callback can be invoked now
}
or consider using promises, which are part of the ES6 standard. If using ES5 or below, there's libraries that can provide promises as well, such as Kris Kowal's Q
You need a callback function... This is an example of callback function
$("button").click(function(){
$("p").hide("slow", function(){
alert("The paragraph is now hidden");
});
});
There is an event when CSS animation ends. And CSS animations are better and faster then jQuery animations.
You can write your animations in CSS, use jQuery to set classes that start the animation and then wait for its end.
See how to detect end of CSS animation
$(".button").click(function(){
$(this).addClass("animate");
$(this).one("webkitTransitionEnd otransitionend oTransitionEnd msTransitionEnd transitionend",
function(event) {
// Do something when the transition ends
});
});
#Radek Pech - Thank you for pointing me in the right direction. I wasn't taking into account the CSS animation timing, which made it look like the callback was being fired early.
Have a look at Javascript callbacks.
In essence you can pass a function as a parameter to another function which can then execute it

Run a line of jQuery after the previous one is complete

I have two lines of jQuery and I need one to run after the previous one is complete.
I know js is read line by line, but the second line is happening too soon.
I can't use jQuery callbacks because these functions unfortunately don't have them.
I tried doing a setTimeout() with a wait for 500ms, 1000ms, and 1600ms, but it didn't seem to work. Visually, the second line took place before the first line was completed.
The element used in the first selector has a css transition of 1s and I want that to finish and then the second line to take place.
Is it possible to do something like:
if transition complete, run js
else wait, then check if transition complete, then if true run js.
Here are the two lines of js:
$('#searchInput').removeClass('slideBack').css('top', 0);
$('#headerTopBar').css('position', 'relative').hide();
If you want to wait for a CSS transition to complete, then you need to use an eventListener for the CSS transitionend event on the object that is doing the transition. That will then provide an event handler callback where you can carry out the second line of code after the CSS transition completes.
$('#searchInput').one("transitionend", function(e) {
$('#headerTopBar').css('position', 'relative').hide();
}).removeClass('slideBack').css('top', 0);
Now, in the real world, not every browser uses the same event name for the transition end event so one typically either installs event handlers for all the possible names of the transition end event or one in your code figure out which name is used in this local browser and then use that variable as the event name.
Note: I use .one() so that this event handler will automatically uninstall itself after it fires. I don't know for sure you want that, but it is often desirable with these types of event notifications.
Here's a more verbose version that listens for all possible transition end event names (for all major browsers):
$('#searchInput').one("transitionend webkitTransitionEnd oTransitionEnd MSTransitionEnd", function(e) {
$('#headerTopBar').css('position', 'relative').hide();
}).removeClass('slideBack').css('top', 0);
.css() does not take a callback, you can use .animate() instead:
$('#searchInput').removeClass('slideBack').animate({top:0},500,function () {
$('#headerTopBar').css('position', 'relative').hide();
});

jquery functions overloading

I have a function binded to a .click() event. Each time the user clicks, the browser fadeOut() the current element and animate() the marginLeft of the new element. For some reason when I click fast on the button which is binded to this click event, in Chrome it jumpes the animation and just go on directly to the next on (only if I click like 5 times in 1 second) and don't add the marginLeft, in this case it causes a major usability issue for the UI. Is there any fallback for this scenario? Like if the animation is not completed directly add it with css() or something like that?
Thanks
E: The click() event calls a function where all the magic happens, if it helps ..
You may want to look into jquery's .stop() method. It allows you to short-circuit any currently-running animations on an element.
Simple example:
$myElement.on('click', function() {
// first 'true' clears animations in the queue for this element
// second 'true' completes the currently-running animation immediately
$(this).stop(true, true).fadeOut();
});
http://api.jquery.com/stop/

Repaint CSS before JavaScript runs (to show progress indicator)

I have a JS routine (triggered by the user) that can take some time to complete. While the routine is running, I want to show a progress overlay on screen. Here's the code that calls the routine (this is called in response to a click event):
function handleClick() {
$('div#progressOverlay').removeClass('hidden');
myBigRoutine();
...
$('div#progressOverlay').addClass('hidden');
}
The class toggle triggers a change in opacity and visibility (animated with a transition).
The class changes themselves are working fine; the first is executed before the slow routine and the second is executed after everything else.
The issue is that the visual appearance of #progressOverlay doesn't change until after myBigRoutine() finishes.
The result is that the progress overlay flashes on screen for a split second and then is immediately hidden again (all with no animation)
Is there a way to force the visual update/repaint to occur before (or, even better, in parallel with) the big JavaScript routine?
You can bind an event to animation finish. So, when animation finishes, only then your code will execute,
function handleClick() {
$('div#progressOverlay').removeClass('hidden');
}
$("div#progressOverlay").bind("animationend webkitAnimationEnd oAnimationEnd MSAnimationEnd", function(){
myBigRoutine();
...
$('div#progressOverlay').addClass('hidden');
});
I hope, this is what you need :)
Your myBigRoutine() function should be called asynchronously.
function handleClick() {
$('div#progressOverlay').removeClass('hidden');
setTimeout(function() {
myBigRoutine();
...
$('div#progressOverlay').addClass('hidden');
}, 150);
}
150 is a magic number that means timeout delay in milliseconds. It can be any small number.
Also, consider using .hide() and .show() jQuery methods instead of hidden class.

Is setInterval() and setTimeout() bad things to do in modern jQuery animations?

I had some problems with animations with jQuery 1.6. I solved it with jQuery 1.5.
In my project I used setInterval() to make custom logo slider. Animations fired up instantly (not simultaneously) two by two. Everything goes smoothly when I am on the page, but when I went on other tab and comeback (after minute, two or so) to my page project everything goes crazy...
Ok, so I got one answer to use Queue(). Can I achieve same thing with that method?
I have book Manning jQuery in Action and there is nothing on instantly fired up animations with Queue().
Link to Jsfiddle
To quote some of that answer:
Because of the nature of requestAnimationFrame(), you should never queue animations using a setInterval or setTimeout loop.
In general setInterval == BAD and setTimeout == GOOD for animations.
setInterval will try play catchup, as nnnnnn stated:
some browsers may queue everything and then try to catch up when your
tab gets focus again
You best method for looping animate() is by calling recursively, for example:
var myTimeout;
var myAnimation = function () {
$('#myID').animate({
[propertyKey]:[propertyValue]
}, 5000, function() {
myTimeout = setTimeOut(myAnimation, 1000);
});
}
Notice how the myTimeout is held outside the scope of myAnnimation allowing the ability to stop the animation
clearTimeout(myTimeout);
Which you could hook up to the window.unload event.

Categories

Resources