Search code examples
javascriptjqueryhovermouseovermove

Infinite move object on mouseover


I'm trying to create a feature where when you mouseover an object, another object begins to move continuously until you mouseout. For some reason in my code it stops after the first 10 pixels, which is this,

http://jsfiddle.net/JoshuaWaheed/7df29/

$("a").mouseover(function(){

    $("div").animate({

        "margin-left": "+=" + 10 + "px"

    });

});

How can I make it run continuously, while on mouseover only?


Solution

  • Don't use .animate, because it's not designed for this. You can move it yourself by altering the CSS in a setInterval loop:

    $("a").mouseover(function () {
        // store the interval ID on the DOM element itself
        $(this).data('tc', setInterval(function () {
            $("div").css({
                "margin-left": "+=1"
            });
        }, 20) // milliseconds
        );
    });
    $("a").mouseout(function () {
        // clear the interval ID
        clearInterval($(this).data('tc'));
    });
    

    http://jsfiddle.net/mblase75/5QJTT/