What does the jQuery selector $ ({}) do?

Question:

I am making an animation and I have found the following pen : CodePen

pen code:

$({percentage: 0}).stop(true).animate({percentage: value}, {
    duration : 2000,
    easing: "easeOutExpo",
    step: function () {
        // percentage with 1 decimal;
        var percentageVal = Math.round(this.percentage * 10) / 10;

        $el.text(percentageVal + '%');
    }
})

Selector:

$({percentage: 0}) .stop(true) .animate({percentage: value}, {...});

  • That changes?
  • What is it for?
  • In case of specifying jQuery properties, what does the percentage ?

I suppose jquery have a JSON of properties and they would be changed like this, but I hadn't seen it before.

Answer:

$({percentage: 0}) is the context in which the animation will work and when you indicate which property is in the animate() method, it will look for the indicated property on the context and apply the animation to it.

If you look closely, you will notice how in the body of step() this is used to access the porcentage property defined in the object passed by the jquery constructor, which is the context:

 step: function () {
             // accediendo al contexto provisto en el constructor de jquery
                                        ↓
        var percentageVal = Math.round(this.percentage * 10) / 10;

        $el.text(percentageVal + '%');
    }

TL; DR {percentage: 0} represents the context sent to the jquery constructor. .animate({percentage: value},{}) represents the property to animate based on context.

Scroll to Top