new2cpp
new2cpp

Reputation: 3677

Please explain the meaning of $({deg: 0}) in JQuery

Could someone explain to me what's the meaning of $({deg: 0}) in CSS rotation cross browser with jquery.animate()?

e.g.

$({deg: 0}).animate({deg: angle}, {
    duration: 2000,
    step: function(now) {
        // in the step-callback (that is fired each step of the animation),
        // you can use the `now` paramter which contains the current
        // animation-position (`0` up to `angle`)
        $elem.css({
            transform: 'rotate(' + now + 'deg)'
        });
    }
});

I'd much appreciate if you could show me the relevant jQuery official documentation about it.

Upvotes: 4

Views: 784

Answers (1)

iCollect.it Ltd
iCollect.it Ltd

Reputation: 93571

It creates a disconnected pseudo jQuery object with the property deg set to 0.

You might have seen this before:

var newDiv = $('<div>', {class: "hello"});

Which creates a specific element type and sets initial properties on it. It is the same thing without the specified element type.

Note: this type of object is not valid for insertion into the DOM, but you can apply many useful jQuery methods to it.

So you can use information from that object to do cool things like this: http://jsfiddle.net/TrueBlueAussie/cfmzau1w/

// Create a pseudo jQuery object (not connected to a DOM element)
var po = $({
    deg: 0
});

// This is just the target object we want to change
$elem = $('#result');

// Use animate on the object, to make use of the step callback
po.animate({
    deg: 360
}, {
    duration: 5000,
    step: function (now) {
        // Take the computed value and use it on a real element!
        $elem.css({
            transform: 'rotate(' + now + 'deg)'
        });
    }
});

The reference is not obvious, but on this page http://api.jquery.com/jquery/#jQuery-object it has a jQuery(object) method that says:

jQuery( object )
object Type: PlainObject
A plain object to wrap in a jQuery object.

In your example the object is your anonymous object so the long-hand pseudo-code of the example is something like:

var anonymousObj = {
     deg: 0
};
var wrappedInAjQueryObject = jQuery(anonymousObj);
wrappedInAjQueryObject.animate(targetPropertiesAndValues, someSettingsAndCallbacksInAnObject);

Upvotes: 6

Related Questions