Question

I am trying to track the mouse position while you are clicking and dragging inside a div, and only while you are clicking and dragging. I used

 $("div").mousedown(function() {
        $("div").mousemove(function(event) {
                $('div').html("( " + event.clientX + ", " + event.clientY + " )");
        });
    })

I have also tried

$("div").bind("mousedown mouseup", function () {
    $("div").mousemove(function (event) {
        $('div').html("( " + event.clientX + ", " + event.clientY + " )");
    });
});

but they both keep tracking the mouse's position even after I let go of the mouse. How can I stop it after I stop clicking?

It's worth noting I have seen the answer from this questions, it won't work for me and I'm not sure why.

JSFiddle

Was it helpful?

Solution

Something like that?

 $("div").mousedown(function() {
    $("div").on('mousemove', function(event) {
       $('div').html("( " + event.clientX + ", " + event.clientY + " )");
    });
 })

 $("div").mouseup(function() {
    $("div").off('mousemove');
 })

http://jsfiddle.net/7G7tx/2/

You bind the event when the mouse button is pressed and unbind it when the button is released.

OTHER TIPS

The problem is that you are not cleaning your event handlers, and instead adding more and more.

Check this out

 $("div").mousedown(function() {
     var mouseMoveHandler = function (event) {
         $('div').html("( " + event.clientX + ", " + event.clientY + " )");
     };

     var mouseUpHandler = function (event) {
         $("div")
             .off('mousemove', mouseMoveHandler)
             .off('mouseup', mouseUpHandler);
     };

     $("div")
         .on('mousemove', mouseMoveHandler)
         .on('mouseup', mouseUpHandler);
 });

http://jsfiddle.net/7G7tx/3/

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top