Search code examples
javascriptjquerymouseeventmousedownmouseup

Javascript-JQuery: stop action when mouse is up?


Here's a bit of my code:

$(".slider").mousedown(function(cursor) {
    $(".slider").mousemove(function(cursor) {
        $(this).css({transform:'rotate('+ degrees(cursor) +'deg)'});  
    });
});

What I want to make the slider move only when the mouse is down and stop when it's up. But in my case, it just keeps moving! Any ideas? Thanks!


Solution

  • You should generally never bind an event handler inside an other event handler, and in this case the mousemove event handler won't stop working after it's bound, just because the mouse is no longer down, once it's bound, it's bound.

    It would be easier to just use a flag and check that

    $(".slider").on({
        mousedown: function() {
            $(this).data('mouse_is_down', true);
        },
        mouseup : function() {
            $(this).data('mouse_is_down', false);
        },
        mousemove : function(cursor) {
            if ( $(this).data('mouse_is_down') ) {
                $(this).css({
                    transform: 'rotate('+ degrees(cursor) +'deg)'
                });  
            }
        });
    });
    

    cursor seems like the event here, so not quite sure how that would work ?