karse23
karse23

Reputation: 4115

cancel event mousedown in javascript / jquery

I'm doing a drag and drop and when the draggable object passes certain limits that I have set to the screen I want to return it to its original position.

My problem is that if the onmousedown event is active the object don't return to its original position until onmouseup event is called.

Is it possible to cancel or stop mousedown while it's running?

Upvotes: 1

Views: 1682

Answers (4)

karse23
karse23

Reputation: 4115

@Voitek Zylinski: your solution works, but I finally found this solution that is better in my case:

$(document).trigger("mouseup");

Thank you.

Upvotes: 0

thalisk
thalisk

Reputation: 7763

Perhaps you may find this jquery.event.drag plugin useful. It allows you to cancel the drag while it is in progress. From its docs:

drag

This event fires after "draginit" and "dragstart" every time the mouse moves. The handler can return false to stop the drag interaction and go straight to "dragend" and also prevent any "drop" events. If dragging multiple elements (from "draginit"), this event will fire uniquely on each element.

Upvotes: 0

Wojciech Zylinski
Wojciech Zylinski

Reputation: 2035

You can clear the mousemove event when a specific condition is met:

function trackMouse(e) {
    if (e.pageX > 200 || e.pageY > 200) {
        // stop execution (event continues to run)
        // alternatively, to detach this event:
        $(window).off('mousemove', trackMouse);
    } else {
        $('#output').html(e.pageX +', '+ e.pageY); 
    }
}

$(window).on('mousemove', trackMouse);​

Demo (JSLint)

Upvotes: 1

jonas
jonas

Reputation: 994

Sounds like you should be using the onmousemove-event to see if you've reached the limit, but are using the onmousedown, which as you say won't fire before you release the mouse button. which is is fired only once as you press the mousebutton

Upvotes: 0

Related Questions