I've this position that is dependent on dynamic value. It makes sense that shorter distance should be animated faster but with appearance of same amount of acceleration (speed). However, in jquery docs I only see a way to define duration which is ok for lots of things but not for others. How can I define speed so if value is small duration is small too and if value is long then duration is long to. thanks.
Asked
Active
Viewed 1,079 times
2

Rick Davies
- 713
- 9
- 22

Muhammad Umer
- 17,263
- 19
- 97
- 168
-
1You can compute the distance that the element will be moved, for example, and use that to determine the length of the animation. Unfortunately there is no native way to determining the "speed" or "rate" of an animation. – Terry Jan 06 '15 at 02:32
-
@Terry I think you mean "there is *no* native way". – Alexander O'Mara Jan 06 '15 at 02:33
-
@AlexanderO'Mara Indeed. Brain fart recorded at 3.34am ;) thanks! – Terry Jan 06 '15 at 02:34
1 Answers
2
Since the jQuery animation only accepts a time, you can calculate the time to give you a specific speed:
time = pixels / desired pixels per second
So, if the animation covers 200px and the desired speed is 100px / sec, then you simply calculate:
time = 200px / 100 px per sec = 2 sec = 2000ms
If the animation covers 40px, then you'd have:
time = 40px / 100 px per sec = 0.4 sec = 400ms
You could also make your own version of jQuery animate that does this work for you using this form of animate(properties, options)
:
jQuery.fn.speedAnimate = function(properties, options, val, rate) {
options.duration = (val / rate) * 1000;
return this.animate(properties, options);
}
Where val
is in any units you care to use (pixels might be most common) and rate
in units/second.

jfriend00
- 683,504
- 96
- 985
- 979
-
Of course, for any shaping other than 'linear', the speed will be an average. – Roamer-1888 Jan 06 '15 at 02:57
-
@Roamer-1888 - Yes. If the OP's wants a truly constant speed, they should pick the 'linear' easing function. – jfriend00 Jan 06 '15 at 03:03