I’m relatively new to jQuery and I’m trying to create a custom jQuery function. The function will rotate images. Simple enough! Here’s how I am calling the function at the moment:
function rotate(degree) {
$(this).css({
"transform": "rotate(" + degree + "deg)",
"-ms-transform": "rotate(" + degree + "deg)", /* Internet Explorer */
"-moz-transform": "rotate(" + degree + "deg)", /* Firefox */
"-webkit-transform": "rotate(" + degree + "deg)", /* Safari and Chrome */
"-o-transform": "rotate(" + degree + "deg)" /* Opera */
});
}
I’d like to call the above function like this:
$(".object").rotate(8);
How would I change the above function to work like this?
There is no need to use
each(). The jQuerycss()function works on the entire set, like almost every jQuery function.Here is (at least close to) the best practice, industry-recognized method of creating new jQuery plugins. The reason that your code was not working is because all you did was declare a global function. To make it so that jQuery objects have access to the function, you have to add the function to the jQuery object itself, so that it will be properly paired with instances of that object, making
thisaccess the current jQuery set. This is done like the following. The funny stuff in the function wrapping everything is done for various reasons you can read about in most jQuery plugin tutorials online. Note that inside jQuery functions, there is no need to do$(this)asthisalready refers to the jQuery matched set.I added an
unrotatefunction so you can remove the css easily as well.pimvdb says that jQuery 1.8 will automatically try prefixes, so it may be that you don’t need anything but the
transformproperty if you’re using that version or higher.