Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to catch mouse-up event outside of element?

Tags:

javascript

I have simple Javascript code, similar to this one:

var mouseIsDown = false; ... function canvasMouseDown(e) {   ...   mouseIsDown = true; } function canvasMouseUp(e) {   mouseIsDown = false; } function canvasMouseMove(e) {   if (mouseIsDown) {     ...   } } 

with implemention my own user interface for tranformations (translations, scalings and rotations) with canvas.

Such implementation within canvasMouseMove() function check mouseIsDown variable. All works fine if user does not release mouse button when the cursor/pointer is outside of the canvas element. If that happen, the variable mouseIsDown stays true and is not turned off by canvasMouseUp function.

What is easy fix or solution in pure JavaScript (no jQuery) for this issue?

like image 798
Ωmega Avatar asked Jul 18 '12 01:07

Ωmega


People also ask

Which event is used when mouse moves over the element?

The mouseover event is fired at an Element when a pointing device (such as a mouse or trackpad) is used to move the cursor onto the element or one of its child elements.

What event handler is called when the user moves the mouse off an element?

The mouseover event occurs when a mouse pointer comes over an element, and mouseout – when it leaves. These events are special, because they have property relatedTarget . This property complements target .

How are mouse events triggered?

Every mouse move over an element triggers that event. click. Triggers after mousedown and then mouseup over the same element if the left mouse button was used.

What are the parameters of mouse up and mouse down event?

Occur when the user clicks a mouse button. MouseDown occurs when the user presses the mouse button; MouseUp occurs when the user releases the mouse button.


1 Answers

If you want to catch the mouseup event somewhere else in the document, you might add an event handler for this to the documentelement. Note that this won't react on mouseup events outside the viewport, so you might want to fire also when the mouse enters the viewport again without a pressed button.

If you want to catch the mouse leaving your canvas element, it gets a bit more complicated. While IE knows a mouseleave event, the standard DOM has a mouseout event that also fires when a descendant of your element is left (although canvas usually has no child elements). Read more on that at quirksmode.org.

I have created a fiddle to demonstrate the behaviour (works only with W3 DOM). You might try to change documentelement to body. In Opera, the mouseup listener on <html> event detects mouseup events outside the document when the "drag" began inside it - I do not know whether that is standard behaviour.

like image 119
Bergi Avatar answered Sep 22 '22 06:09

Bergi