Barrie Reader
Barrie Reader

Reputation: 10713

jQuery rotation function not firing.

I have the following jQuery extension:

(function ($) { //jQuery plugin extension

    jQuery.fn.rotate = function(degree, maxDegree) {
        this.css({ WebkitTransform: 'rotate(' + degree + 'deg)'});
        this.css({ '-moz-transform': 'rotate(' + degree + 'deg)'});

          // Animate rotation with a recursive call
        rotation = setInterval(function() { 
            if (degree < (maxDegree/2)) { 
                $(this).rotate(++degree);
            } else {
                clearInterval(rotation);
            }
        },5);
    };
}(jQuery));

And I'm calling it like this:

$('#test').live('mouseover',function() {
                $(this).rotate(0, 360);
            });

But it doesn't fire, here is a JSFiddle: http://jsfiddle.net/neuroflux/8vZqr/

( Note, the fiddle won't run because of the live() )

Upvotes: 1

Views: 1193

Answers (2)

Felix Kling
Felix Kling

Reputation: 816930

You are not calling the function you have your plugin in:

(function ($) {
    $.fn.rotate = function(degree, maxDegree) {
        //...
    };
}(jQuery)); // <-- call

Furthermore, this inside the setInterval method does not refer to the selected elements anymore, but to window. You have to keep a reference to this:

var $self = this;
var rotation = setInterval(function() { 
    if (degree < (maxDegree/2)) { 
        $self.rotate(++degree);
     //...
};

I would als make rotation a local variable (with var) otherwise you will get in trouble if the function fires on several elements.

As for your fiddle, you did not select jQuery to use as library.

If this is all fixed, it works → .

Upvotes: 2

ChristopheCVB
ChristopheCVB

Reputation: 7315

You can also have a look to that jQuery plugin :

http://www.zachstronaut.com/projects/rotate3di/

Upvotes: 1

Related Questions