Reputation: 19057
How do you track mouse motion after mousedown until mouseup using JQuery? Tracking should start when some target element is clicked and continue to mouseup, even when the mouse moves out of the target element.
<div id="some_elt">
<div id="target">
</div>
</div>
The only way I can think of is binding mousemove
to the whole document and invoking my motion handler based on a global flag I set from $("target").mousedown
and unset from$("target").mouseup
.
Is there a more elegant approach than this?
Edit: I think I need to add an extra bit... my target already has draggable()
applied to it. I'm trying to make a decent image viewer. I have a viewport div
containing a draggable img
. I'm trying to do make the image zoomable with something like shift+middle-click, without interfering with the draggable for navigating. Am I going to have to piggyback on stuff that JQuery does under the hood to make draggable work?
Edit2: To answer my edit: of course not! JQuery is awesome!
Upvotes: 3
Views: 1654
Reputation: 171698
Use event target to start tracking
$(document).mousedown(function(event){
if( event.target.id=="target"){
$(this).on('mousemove',function(event){
/* do tracking*/
})
}
}).mouseup(function(){
$(this).off('mousemove');
})
For versions of jQuery less than 1.7
$(document).mousedown(function(event){
if( event.target.id=="target"){
$(this).mousemove(function(event){
/* do tracking*/
})
}
}).mouseup(function(){
$(this).unbind('mousemove');
})
Upvotes: 3
Reputation: 2797
I think one of the most elegant way is to use the jQuery UI draggable:
$("#target").draggable({
start: function(event, ui) { console.log("start dragging"); },
drag: function(event, ui) { console.log("continue dragging"); },
stop: function(event, ui) { console.log("stop dragging"); }
});
Upvotes: 2