I’m using this JS animated counter. At the moment there only seems to be two options for the animation – "linear" or "swing".
There seems to be very little JS defining this so it feels like I’m missing something. How can I make it ease out instead of using linear or swing?
From what I can tell this is the block that controls the easing:
function doCount(num, index, speed, groupClass, direction, easing) {
let className = groupClass + ' ' + counterClass + '.' + 'c_' + index;
if(easing == undefined) easing = "swing";
$(className).animate({
num
}, {
duration: +speed,
easing: easing,
step: function (now) {
if (direction == 'reverse') {
$(this).text(num - Math.floor(now));
} else {
$(this).text(Math.floor(now));
}
},
complete: doCount
});
}
The variable easing
is just calling in the data attribute which is either set to linear by default or swing.
I’ve tried just adding "easeOut" but no luck with that hit and hope!!
2
Answers
As highlighted in the comments above, jQuery by itself only supports two types of easing functions,
linear
andswing
. This is outlined here in the jQuery documentation, which also points out that you can add additional easing functions by including jQuery UI in your project, this could be done by including the jQuery UI CDN in addition to the standard jQuery library:Once you’ve included jQuery UI, you can use the easing functions it provides. There are a number of easing functions you can use, and you can find a list of each easing function and its implementation by logging the
$.easing
object. A list is also included in the docs:You can then use one of these easing functions for your counter, eg:
See example below:
Note that you don’t need to include the entire jQuery UI library in your project and can instead select just the Effects core component for just the easing functions, which you can do on their download page here.
The standard library only supports 2 options,
swing
andlinear
.But jquery UI library supports many options for easing attribute. You can choose the below one.
easeOutExpo
,easeOutQuint
,easeOutQuart
,easeOutCubic
,easeOutQuad
…Don’t forget to import jquery-ui script.
You can check more options here with examples.
https://api.jqueryui.com/easings/