jQuery Queue Functions - javascript

Take these two methods:
function moveUp() {
this.element.rotate(0);
this.element.animate({"margin-top": "-=51px"}, "slow");
//do some more things for instance.
}
function moveRight() {
this.element.rotate(90);
this.element.animate({"margin-left": "+=51px"}, "slow");
}
Just in case, I rotate an object, then move it around with an animation. These functions are mapped to key presses, so if the user presses Up or Right, the object moves. My problem is that the animations are queued properly, because jQuery uses the fx queue for them. But the rotation happens inmediately, as well as any other thing I do, since they are custom things I have in my code.
The consequence is obvious, if you press say up and immediately press right, the object rotates up, but while it is moving upwards, it rotates right, it doesn't really wait until it gets there.
How can I write this code so that the whole methods are chained and not just their animations. I could add callbacks, but they won't always execute together, I need them to be queued if they happen to be called simultaneously, but I don't quite understand how to use the queue functionality in jQuery.
By the way, to see more of the code behind this, I have recently asked this question also: Array of prototype functions

You could animate it using something like:
$elem.animate({rotation: 90},
{
duration: 'slow',
step: function(now, fx) {
$(this).css({ "transform": "rotate("+now+"deg)", "-webkit-transform": "rotate("+now+"deg)", "-moz-transform": "rotate("+now+"deg)" });
}
})
That would add it to the queue automatically
I've made a jsfiddle here:
http://jsfiddle.net/obartra/7Qwgd/1/
EDIT: Just to explain my rationale, I'm guessing that the rotate method you are using is using setTimeout to set the rotation in the CSS progressively, thus not adding it to the animation queue. The code here uses animate to rotate the element so it gets added to the animation queue.

Related

Interval doesn't clear immediately after repeating for a while

I have a bouncing arrow on my website that I created with Jquery and setInterval, like this:
bouncing = setInterval(function() {
$("div").animate({
top:"30px"
},100,"easeInCubic",function() {
$("div").animate({
top:"0px"
},100,"easeOutCubic");
});
console.log("bounced");
},200);
You can see this in place in a codepen here: http://codepen.io/mcheah/pen/wMmowr
I made it run faster than i needed because its easier to see the issues quicker. My issue is that after leaving the interval running for a few seconds, you'll notice that instead of bouncing back up or down immediately, the bouncing element will stop for half a second and then just hang there, before beginning again. If you leave it running even longer (20 seconds) and then clear the interval, you'll notice that it takes a few seconds to stop bouncing.
My questions are these:
Why does the bouncing go out of sync occasionally?
Why does the clear interval take a while to clear if it's been repeating for a while?
Is there a better way to have a bouncing arrow? Are CSS transitions more reliable?
Thanks for your help!
Your are trying to perfectly coordinate a setInterval() timer and two jQuery animations such that the two come out perfectly coordinated. This is asking for trouble and the two may drift apart over time so it is considered a poor design pattern.
If, instead, you just use the completion of the second animation to restart the first and make your repeat like that, then you have perfect coordination every time.
You can see that here in another version of your codepen: http://codepen.io/anon/pen/NxYeyd
function run() {
var self = $("div");
if (self.data("stop")) return;
self.animate({top:"30px"},100, "easeInCubic")
.animate({top:"0px"}, 100, "easeOutCubic", run);
}
run();
$("div").click(function() {
// toggle animation
var self = $(this);
// invert setting to start/stop
self.data("stop", !self.data("stop"));
run();
console.log("toggled bouncing");
});
It's not a good idea to mix animate() with timers this way. There's NO chance you can synchronize something like this. And there's no need to. You can simply append a function into the animation queue, look here: https://stackoverflow.com/a/11764283/3227403
What animate() does is put an animation request into a job queue which will be processed later, when the right time comes. When you break the interval the stuff that accumulated in the queue will still be processed. There's a method to clear the queue and stop all animation immediately.
The JQuery animation functions actually manipulate CSS, and there is nothing beyond it in HTML. Another option would be using a canvas, but it is a completely different approach and I wouldn't recommend it. With JQuery's animation your already at the best choice.
This is a simple solution to your problem:
function bounce()
{
$("div")
.animate({
top: "30px"
}, 100, "easeInCubic")
.animate({
top: "0px"
}, 100, "easeOutCubic", bounce); // this loops the animation
}
Start bouncing on page load with:
$(bounce);
Stop bouncing on click with:
$("div").click(function() {
$("div").stop().clearQueue().css({ top: "0px" });
// you want to reset the style because it can stop midway
});
EDIT: there were some inaccuracies I corrected now. The running example is on codepen now.
If you want to use javascript for animation you can use something better like the greensock tween library
http://greensock.com/docs/#/HTML5/GSAP/TweenMax/to/
something like this:
var tween = TweenMax.to($("div"), 100, {y: "100px", yoyo: true, repeat: -1});
You could wrap your interval code with:
if(!$("div").is(":animated"))
This will initiate your animation only if your previous one is finished.
The reason why it was bouncing weird is that your animations are queued.
You can check how it works now:
http://codepen.io/luminaxster/pen/XKzLBg
I would recommend using the complete callback when the second animation ends instead and have variable to control a bounce recursive call in this version:
http://codepen.io/luminaxster/pen/qNVzLY

Make sure only one animation is being fired

I am running this animation on $(window).scroll() and it works fine for the most part.
$('#el').animate({ left: toMove }, 500);
The problem is if the user scrolls too fast, two animations will fire and the second animation will fire before the first one has moved far enough. How can I make sure there is only one animation at any given time and then the other animations will follow? I need the element to animate left FULLY any other animations run but I need them all to run. I tried using .queue() but couldn't find the right solution with it.
You could use the stop function like this to smooth things up:
$('#el').stop(true, false).animate({ left: toMove }, 500);
The stop function, when calling like that will clear the animation queue for any waiting animation, as well as stop the current animation if any.
Edit
If you want the animation to end before animating again you just need to call .stop(true, true) instead

jquery animate callback not executing until final loop

I made a small test code using the jquery transit plugin for animations.
The purpose of the script is to have a photo of a tower make a flip 90 degrees toward the user, switch to another tower image, and flip another 90 degrees to lay flat on the screen. The issue is that after the first 90 degree flip, the image disappears entirely until the for loop has concluded before doing the final flip as the second image. I'm looking to have it flip continuously until the loop is finished.
I imagine this has something to do with closures and scope...
Javascript:
$(function() {
for (var i = 0; i < 10; i++) {
$('#test_flip')
.css('background-image', 'url("tower1.jpg")')
.transition({
rotateY: '90deg'
}, function() {
$('#test_flip')
.css('background-image', 'url("tower2.jpg")')
.transition({
rotateY: '180deg'
});
});
};
});
jsfiddle: http://jsfiddle.net/ce9b9aja/
The issue lies in the fact that the for loop calls .transition 10 times consecutively. The calls are queued in the jQuery queue (which is done behind the scenes by transit.js), but they are not queued in the order you're expecting.
Take the following example:
$(function () {
$('#test').transition({x:40}, function () {
$(this).transition({y:40});
})
$('#test').transition({scale:0.5}, function() {
$(this).transition({skewX:"50deg"});
});
});
#test {
width: 10em;
height: 10em;
background-color: gray;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<script src="http://ricostacruz.com/jquery.transit/jquery.transit.min.js"></script>
<div id="test"></div>
In this example, the first transition x:40 will be executed instantly because there is no queue. Despite the fact that it is executed instantly, since it is an animation, it will be using some form of setTimeout or setInterval and will not be completed in the transition method call. Consequently, the scale:0.5 transition will be called while the x:40 transition is still animating, which will put it in the queue it before y:40 is put in the queue.
Therefore, the queue order is
x:40 -> scale:0.5 -> y:40 -> skewX:50deg
Similarly, your code is producing the following queue:
rotateY:90deg -> ... -> rotateY:90deg -> rotateY:180deg -> ... -> rotateY:180deg
Thus your code's behavior. It rotates the image 90deg first, then it does it 9 more times, which doesn't change anything visually (hence the "pause"). Then it changes the image and rotates it 180deg and does that 9 more times also.
One solution could be to create a recursive function using the callback of the .transition function. An example is implemented below:
$(function() {
FlipMe($('#test_flip'), "http://i.imgur.com/tYYtwbi.jpg", "http://i.imgur.com/G4CvJpc.jpg", 10)
});
function FlipMe($el, image1, image2, times) {
$el.css('background-image', 'url("'+image1+'")')
.transition({rotateY: '90deg'}, function() {
$el.css('background-image', 'url("'+image2+'")')
.transition({rotateY: '180deg'}, function() {
if(times > 0) {
FlipMe($el, image2, image1, times - 1);
}
});
});
}
Updated fiddle here: http://jsfiddle.net/ce9b9aja/1/
The code above exclusively uses callback functions to dictate the order of events. When the first transition is completed, the callback function will "queue" the next transition, which will be executed instantly since nothing else will be in the queue. And so on.

.fadeIn() / fadeOut() on mousemove

I got a problem with smooth fadeIn and fadeOut in mousemove... I am doing some calculations about what is under top element, and based on those calculations I would like to fadeIn() or fadeOut() tooltip. The problem is that when moving a mouse, events are being shoot like every few milliseconds.
The sitiuation looks like this:
I move the mouse, tooltip is hidden. Suddenly mouse pointer is on top of element that should trigger fadeIn(), but this element is not the triggerer, because it is behind of some other element. So I need to shoot fadeIn() from mousemove. But, when I shoot it, every few milliseconds, it doesn't work, or works million times. But generally, it does not... animation simply stucks as long as I move mouse, because fadeIn() is being called all over again. I am really tired of this, tried to fix it for like 5 hours and nothing.
I've tried:
.stop() before fadeIn() / fadeOut() in different configurations... but the only visible effect I got was that it looked like show(), because stop(true,true) simply deletes the queue and leads to the end of last animation. So, wow! It is show... how... eghn... great :/
Using :visibe selector to fadeOut() and :not(:visible) to fadeIn() ... well.. that of course did not change much, an with stop() it was just leaving semitransparent tooltip
Using rel attribute to define that the fadeOut() was already shoot and should not be shoot anymore... even worse idea, because it simply did not come back after total fadeOut()
To get some reset and thing, but I can't rest when I don't have this problem resolved - it is sooo annoying!
I wonder if anybody reads this anyway... I wouldn't.
So HOW to limit fadeOut(), fadeIn() events to one each time so it would smoothly fadeIn and fadeOut even from middle of animation when event is triggered by mousemove?
I will probably get -1000 for this question... doooh.
I'd suggest you use css for this instead. You lose a bit of compatibility (Most notably older IE's), but it's simpler and will run a lot smoother.
E.g. define opacity in a :hover pseudo class, and then define a transition property with a timing of your choice.
Edit:
Using css in this case has no use because as I said, the event is not trigered by top most layer... stop(true,true) works exactly te same as show() because it is called every few milliseconds, and once is enough to stop fade effect.
In that case, set/unset a class on the fading-element inside your event handler. Let css do the work for you.
E.g.:
<style>
#tooltip { opacity:0 ; transition:opacity 1s linear }
#tooltip.enabled { opacity:1 }
</style>
<div class="has-tooltip">Foo</div>
<div id="tooltip">Tooltip</div>
<script>
$(".has-tooltip")
.on("mouseenter", function() { $("#tooltip").addClass("enabled") })
.on("mouseleave", function() { $("#tooltip").removeClass("enabled") })
</script>
You can try to unbind events before FadeIn/fadeOut and bind again after animation is complete (in complete function).
try this, call this function on mouse move
TIMER='';
function onmove()
{
if(TIMER)
clearTimeout(TIMER);
else
TIMER = setTimeout(function(){
// use yor code here eg. $('whteverID').fadeIn();
},10)
}

jquery - how to queue up a series of css property changes

I want to set a series of animation properties - a list of names that are currently invisible but will be marked visible, one right after another, with a set delay of about 100ms between each other. How do I accomplish this with jquery? Essentially, it would be something like this (pseudo-code):
for each $(.item) {
$(this).delay(index*100ms).css({'visibility': 'visible'}
}
The only thing that might compound this, while most of the elements would have the same class, not all of them would, so an animation queue of some sort would work best.
You can use .delay() to do this.
$('#foo').slideUp(300).delay(800).fadeIn(400);
When this statement is executed, the element slides up for 300 milliseconds and then pauses for 800 milliseconds before fading in for 400 milliseconds.
You actually want to do one thing to multiple items, so this is how I'd do that:
$.each($(".a"), function(index, value) {
$(this).delay(index*400).fadeOut(400);
});
You were on the right track with your pseudocode, you need to offset each animation by index * someTime.
Turns out, .delay() actually doesn't work with css() so here's an updated solution:
$.each($(".a"), function(index, value) {
$(this).delay(index*400).queue( function(next){
$(this).css('visibility','visible');
next();
});
});
demo

Categories