0

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

Community
  • 1
  • 1
EasilyBaffled
  • 3,822
  • 10
  • 50
  • 87

2 Answers2

1

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.

Getz
  • 3,983
  • 6
  • 35
  • 52
1

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/

Anton Boritskiy
  • 1,539
  • 3
  • 21
  • 37