I've been struggling with this issue for awhile and have decided to ditch the setTimeout approach since I just read creating too many timers is bad. Below is the function to animate a group of objects - which is called on hover. It's currently setup so that all animation settings are passed in from the user and apply to the correct object, then each object is animated on a per-property basis - allowing for control of speed in/out and easing for each property.
The only thing I'm working on now is the delays. I can't use .delay since it isn't queued and I can't use setTimeout (at least in the approach I've taken). Any ideas?
function animate_in(e){
$(this).find('.captionator_background').each(function(index){
// LOOP THROUGH OBJECTS
current_obj = $(this); current_obj.stop().clearQueue();
// 1. LEFT ANIMATION
current_obj.animate({'left':ends_x_set[index]},{duration:parseInt(bg_x_speed_in_set[index], 10), queue:false, specialEasing: {'left':bg_x_ease_in_set[index]}});
// 2. TOP ANIMATION
current_obj.animate({'top':ends_y_set[index]},{duration:parseInt(bg_y_speed_in_set[index], 10), queue:false, specialEasing: {'top': bg_y_ease_in_set[index]}});
// 3. OPACITY ANIMATION
current_obj.animate({'opacity':parseInt(end_opacity_set[index], 10)},{duration:parseInt(opacity_speed_in_set[index], 10), queue:false, specialEasing: {'opacity':opacity_ease_in_set[index]}});
// 4. BACKGROUND COLOR ANIMATION
current_obj.animate({'backgroundColor':bg_color_in_set[index]},{duration:parseInt(bg_color_speed_in_set[index], 10), queue:false, specialEasing: {'backgroundColor':bg_color_ease_in_set[index]}});
}); // END EACH LOOP
}; // END ANIMATE IN FUNCTION
Thanks!
Related
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
So here is the scenario. I'm trying to make a infinite image carousel, and everytime it will show an image that has a class of special .special I want to slow down the animation duration or the scrolling of the animation. So users can see the special image longer. Here is my code.
$photoGalleryList.animate({
left : '-' + (computedWidth) + 'px'
},
{
duration : 10000,
easing : 'linear',
step : function(now, fx) {
if(visibleSpecialImage()) {
// SLOW ANIMATION DURATION
// Tried setting fx.options.duration still no effect
}
}
});
I'm not sure if my approach is right (doing it with step), jquery animate() documentation says
step
Type: Function( Number now, Tween tween )
A function to be called for each animated property of each animated element. This function provides an opportunity to modify the Tween object to change the value of the property before it is set.
I'm not sure if I understood the documentation clearly, But base on what I read it's possible using step, I tried googling my problem and never found any concrete answer So now I'm stackoverflowing and hopefully solve this problem. Thanks
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.
I am new in KineticJS and I am stacked. I want to use a simple animation with opacity but I found out that there is not so "simple" as it seems. I read the doc about animations with KineticJS (you won't say simple about this tutorial). What I want to know Is there a simple method to animate things with KineticJS like JQuery or JCanvaScript has? for example
this.animate({
opacity:0,
x: 50
}, 500);
something like this?
If there is not can we use KineticJS with JQuery to make animations simple? I found out THIS project that has very interesting piece of code:
$(logo.getCanvas()).animate({
opacity: 1,
top: "+=50px"
}, 1000);
so guys what do you think? Is it buggy to use this method?
If you just have to do your opacity animation : you should stick to JQuery which will hide the computations done for the animation (and what you were pointed to is a good solution).
If you want more controls over your animation : go with KineticJS.
Through, I think you will have more issues trying to use JQuery animations and KineticJS layers at the same time rather than using only KineticJS (and Kinetic.Animation is pretty simple once you have understand how to play with it)
edit: Quick How-To for animations :
So, as you may have seen, in Kinetic, you do not give the final position like in JQuery : you have an access to a function which is called at each frame of the animation and all the logic have to be placed in it :
<script>
// you should have an object yourShape containing your KineticJS object.
var duration = 1000 ; // we set it to last 1s
var anim = new Kinetic.Animation({
func: function(frame) {
if (frame.time >= duration) {
anim.stop() ;
} else {
yourShape.setOpacity(frame.time / duration) ;
}
},
node: layer
});
anim.start();
</script>
What I want to do is when I stop an animation to
reset the initial state of the animated object. I want to do that because when I stop it now (Element.stop([anim])) it freezes in its current point (lets say half tranperant) and when I play it again the animation starts to repeat from this place not from the beginning.
Here is my animation Raphael.animation({opacity: 0}, 500, "<>").repeat(Infinity).
I asked this question in the Raphael newsgroup 3 weeks ago but I didn't receive any answer.
Thanks,
bozhidarc
I'm not suggesting it's the most elegant, but in the past I've done things like this simply by adding a couple of extra attributes to the element when you create it. In this case, I'd just add a baseAttrs attribute, which holds the original object of settings:
var paper = Raphael('canvas', 500, 500);
var circle = paper.circle(320, 240, 60);
circle.baseAttrs = {fill:'yellow'}; // add to the elem
circle.attr(circle.baseAttrs);
circle.animate({fill: "blue"}, 1000,
function(){
this.attr(this.baseAttrs);
});
In the above example, the callback from the animation sets the attributes of the circle to the baseAttrsvalue of the element when the animation is complete. The baseAttrs will always be held with the circle, regardless of what happens to it. http://jsfiddle.net/UVPeh/