RogerWu
RogerWu

Reputation: 71

Animating on hover

How can I make hover() run continuously? I'd like that when I mouse over #up_btn, the top property keeps animating. Right now, it only runs once.

$(document).ready(function(){
    $("#up_btn").hover(function(){
        var new_num = parseInt($("#move_box").css("top"));
        $("#move_box").css("top", new_num + 1);
    })
})

Upvotes: 0

Views: 114

Answers (3)

Waleed Khan
Waleed Khan

Reputation: 11467

Use setInterval or setTimeout. For example:

var move_box_interval;
$(document).ready(function() {
    $("#up_btn").hover(function() {
        // Change the interval to be appropriate. It's in milliseconds.
        move_box_interval = setInterval(move_box, 100);
    });

    // Change this to the appropriate trigger.
    $("#up_btn").mouseout(function() {
        clearInterval(move_box_interval);
    });
});

function move_box() {
    $("#move_box").css("top", "+= 1");
}

Upvotes: 1

Ry-
Ry-

Reputation: 224859

You can use setInterval to make your code run repeatedly, then use clearInterval to stop the animation:

$(document).ready(function() {
    var timer;

    $("#up_btn").hover(function() {
        timer = setInterval(function() {
            $("#move_box").css('top', '+= 1');
        }, 100); // Change the interval as you see fit.
    }, function() {
        clearInterval(timer);
    });
});

Upvotes: 2

Tooraj Jam
Tooraj Jam

Reputation: 1612

$(document).ready(function() {
    $("#up_btn").mouseenter(function() {
        var new_num = parseInt($("#move_box").css("top"));
        $("#move_box").css("top", new_num + 1);
    })
})

Upvotes: 0

Related Questions