Hopeless
Hopeless

Reputation: 395

jquery.animate is only working once

I have an image which rotates 360 degrees using .hover, however the animation will only occur once. Here's a little fiddle.

Here's a little fiddle

I am not sure how to fix this, I think its to do with animation itself being finished and needing to be restarted but.

$('#PSLogo').hover(function () {
    $('#PSLogo').animate({
        rotate: 360
    }, {
        step: function (now, fx) {
            $(this).css('-webkit-transform', 'rotate(' + now + 'deg)');
        },
        duration: 'slow'
    }, 'linear');
});

Is the code for the rotation

Upvotes: 2

Views: 290

Answers (3)

Brewal
Brewal

Reputation: 8189

I'm completing Ben's answer about your initial animation. It could be done much simpler with a recursive function call :

function startingAnimation($el) {
    $el.animate({
        width: '100px',
        height: '100px',
        top: '0',
        left: '0'
    }, function() {
        $next = $el.next('img');
        if ($next.length) {
            startingAnimation($next);
        }
    });
}
$(document).ready(function () {
    startingAnimation($('#PSLogo'));
});

Also if you want the animation only on mouseenter and not mouseleave you have to add the transition rule to the hover only.

jsFiddle Demo

Upvotes: 1

Lennart
Lennart

Reputation: 1560

Using plain css would be the easier approach here, but incase you have a valid reason for needing this, this should do it:

var interval = "";

$('#PSLogo').hover(function () {
    interval = setInterval("animate()",1000);
});

$('#PSLogo').on("mouseleave", function () {
    clearInterval(interval);
});

function animate(){
    $('#PSLogo').animate({
        rotate: 360
    }, {
        step: function (now, fx) {
            $(this).css('-webkit-transform', 'rotate(' + now + 'deg)');
        },
        duration: 1000
    }, 'linear');
}

Upvotes: 0

Ben Fortune
Ben Fortune

Reputation: 32118

Why not just use CSS3 transforms? Javascript seems a little heavy for a simple transform.

#PSLogo {
    width:0;
    height:0;
    position:relative;
    top:0px;
    left:0px;
    transition: all 0.5s linear;
}
#PSLogo:hover {
    -webkit-transform: rotate(360deg);
}

If you want it for all of them you can use

.logo {
    transition: all 0.5s linear;
}
.logo:hover {
    -webkit-transform: rotate(360deg);
}

And just add the .logo class to the elements you want.

Fiddle

Upvotes: 5

Related Questions