Antoni4040
Antoni4040

Reputation: 2319

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!

Upvotes: 1

Views: 463

Answers (2)

adeneo
adeneo

Reputation: 318352

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 ?

Upvotes: 1

navotgil
navotgil

Reputation: 329

Add to your code

$(".slider").mouseup(function(cursor) {
    $(".slider").unbind("mousemove");
});

Upvotes: 1

Related Questions