Reputation: 825
Hello everyone I have this code working fine but I want the script to stop on the mouse up event.
Here is an example of what I have now. How can I stop the script on mouse up event so that it looks like it only shows the coordinates when dragging over the image.
Thank you!
$(document).ready(function () {
$("#map-catcher").mousedown(function (e) {
$("#map-catcher").mousemove(function (e) {
$("#coord").text("x:"+e.offsetX+", y:"+e.offsetY);
return;
});
$("#map-catcher").mouseup(function (e) {
return;
});
});
});
Upvotes: 2
Views: 186
Reputation: 48415
Using the mousemove event args
I think the easiest way would be to check the event args for the mousemove event, you should b able to determine if the mouse button is down or not...
$(document).ready(function () {
$("#map-catcher").mousemove(function (e) {
if (e.which == 1) {
$("#coord").text("x:" + e.offsetX + ", y:" + e.offsetY);
}
});
}
NOTE: I am not 100% sure about the cross-browser compatibility of this method (tested in Chrome)
Using a global flag
If this doesn't work the way you want it to, you could try it with a global flag that ca track if the mouse is current down or not...
var moveMode = false;
$(document).ready(function () {
$("#map-catcher").mousedown(function (e) {
moveMode = true;
});
$("#map-catcher").mousemove(function (e) {
//only set the coordinates when the flag is true
if (moveMode) {
$("#coord").text("x:" + e.offsetX + ", y:" + e.offsetY);
}
});
$("#map-catcher").mouseup(function (e) {
moveMode = false;
});
});
NOTE: This may cause some buggy effects if you release the mouse outside of the "#map-catcher"
element. It might be a good idea to change the mouseup
event to work on a document
level instead. Like this:
$(document).mouseup(function (e) {
moveMode = false;
});
Upvotes: 3
Reputation: 1958
Take your event bindings out of the mousedown handler. Furthermore, use .on() syntax, and If I were you I would use mousedown and mouseup to add and remove a class, that is bound to mousemove.
$('parent').on('mousedown', 'element', function(){
$(this).addClass('active');
});
$('parent').on('mouseup','element', function(){
$(this).removeClass('active');
});
$('parent').on('mousedown','element.active', function(){
$(this).goCrazy();
});
Upvotes: 0