Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mouseup not working after mousemove on img

I'm trying to do a simple drag script. The idea is to save the position when the mouse is down, update the view while the mouse is moving, and stop when mouse is up. Problem, mouseup event isn't working properly.

See the code:

var target = $('a')
var pos = 0;
var dragging = false;

$(document).mousedown(function(e) { pos=e.pageX; dragging = true })
$(document).mouseup(function() { dragging = false })
$(document).mousemove(function(e) {
    if(dragging){ 
        target.css('left', e.pageX-pos);
    }
})  ​

Why mouseup works with a "a" tag: http://jsfiddle.net/leyou/c3TrG/1/

And why mouseup doesn't work with a "img" tag: http://jsfiddle.net/leyou/eNwzv/

Just try to drag them horizontally.

Same probleme on ie9, ff and chrome. Windows7

like image 313
leyou Avatar asked Nov 05 '12 16:11

leyou


People also ask

How do I trigger a mouseup event?

The mouseup event occurs when the left mouse button is released over the selected element. The mouseup() method triggers the mouseup event, or attaches a function to run when a mouseup event occurs. Tip: This method is often used together with the mousedown() method.

Does mouseup fire before click?

Mouseup is always firing before click, despite this order.

What is mouseup event?

The mouseup event is fired at an Element when a button on a pointing device (such as a mouse or trackpad) is released while the pointer is located inside it. mouseup events are the counterpoint to mousedown events.


1 Answers

Just add e.preventDefault() to your mousedown handler, like this:

var target = $('img')
var pos = 0;
var dragging = false;

$(document).mousedown(function(e) { e.preventDefault(); pos=e.pageX; dragging = true })
$(document).mouseup(function() { dragging = false })
$(document).mousemove(function(e) {
    if(dragging){ 
        target.css('left', e.pageX-pos);
    }
})

See working demo .

The rationale for the fix is, that the browser was also doing his own native image drag-and-drop (like when eg. you drag an image out of the browser to drop it in an external application) so you need to cancel that default native drag-and-drop with .preventDefault() .

like image 138
Nelson Avatar answered Sep 19 '22 05:09

Nelson