Reputation: 3882
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.
Upvotes: 0
Views: 345
Reputation: 1569
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);
});
Upvotes: 1
Reputation: 4063
Something like that?
$("div").mousedown(function() {
$("div").on('mousemove', function(event) {
$('div').html("( " + event.clientX + ", " + event.clientY + " )");
});
})
$("div").mouseup(function() {
$("div").off('mousemove');
})
You bind the event when the mouse button is pressed and unbind it when the button is released.
Upvotes: 1