Exploring mousemove event arguments
One approach is to utilize the event arguments of the mousemove event in order to determine whether the mouse button is being held down or not.
$(document).ready(function () {
$("#map-catcher").mousemove(function (e) {
if (e.which == 1) {
$("#coord").text("x:" + e.offsetX + ", y:" + e.offsetY);
}
});
}
A live demonstration can be found here
Please note that the compatibility of this method across different browsers has not been extensively tested, so caution should be exercised.
Implementing a global flag
If the previous technique does not meet your requirements, you could consider employing a global flag to keep track of the current state of the mouse button.
var moveMode = false;
$(document).ready(function () {
$("#map-catcher").mousedown(function (e) {
moveMode = true;
});
$("#map-catcher").mousemove(function (e) {
//only update the coordinates when the flag is true
if (moveMode) {
$("#coord").text("x:" + e.offsetX + ", y:" + e.offsetY);
}
});
$("#map-catcher").mouseup(function (e) {
moveMode = false;
});
});
View a working example here
Keep in mind that this approach may lead to unexpected behavior if the mouse button is released outside of the "#map-catcher" element. To mitigate this issue, it might be advisable to bind the mouseup
event at the document
level instead. For instance:
$(document).mouseup(function (e) {
moveMode = false;
});