Why does this Javascript not recognise the mouse up? - javascript

I have the following Javascript code. If inside the div you press the middle and right mouse button down at the same time them move outside the browser with both buttons still pressed you then release one of them. This is recognized. But if you release the other this is not recognized. Is there either a way of recognizing the release of the second mouse button or alternatively when the mouse is moved back into the browser window to be able to find out what buttons are up/down so the state can be updated.
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
</head>
<body>
<div style="height:250px;background-color: pink"> </div>
<script type="text/javascript">
var doc = $(document);
var buttons = [ false, false, false ];
function mouseDown(e) {
buttons[e.which - 1] = true;
console.log(buttons);
e.preventDefault();
}
function mouseUp(e) {
buttons[e.which - 1] = false;
console.log(buttons);
e.preventDefault();
}
doc.on("mousedown", mouseDown);
doc.on("mouseup", mouseUp);
</script>
</body>
</html>
EDIT
The code is here
EDIT 2
Alternatively does anybody know why this is not possible and any references that state that this is not possible.

You can use the document's mouseenter and event's buttons property to figure out which button is down when you re-enter the document:
doc.on("mouseenter", function(e) {
console.log("mouseenter: " + e.target + " buttons: " + e.buttons);
//if (Object.prototype.toString.call(e.target) == '[object HTMLHtmlElement]') {
if (e.buttons == 1){
//left button
}
if (e.buttons == 2){
//right button
}
if (e.buttons == 4){
//middle
}
}
});
See this link for buttons property of the mouse events.
Update:
Link above: A number representing one or more buttons. For more than one button pressed, the values are combined. so
if (e.buttons == 1){
//left button
}
else if (e.buttons == 2){
//right button
}
else if (e.buttons == 4){
//middle
}
else if (e.buttons == 3){
//left and right
}
else if (e.buttons == 6){
//middle and right
}
else if (e.buttons == 7){
//all 3
}
Update 2:
The reason 2nd mouse up isn't registered is because after 1st mouse up, browser stops listening to mousemove events. Try your scenario in the question with these handlers below. mouse move will keep triggerring until you let go the 1st button. As soon as you release the first button, move doesn't get triggered anymore. I thought I could use setCapture or focus on mouse up to make the window continue watching the mouse but it doesn't work.
window.addEventListener("mouseup", function( event ) {
console.log("window mouse up");
//window.focus();
//event.target.setCapture(true);
}, false);
window.addEventListener("mousemove", function( event ) {
console.log("window mouse move");
}, false);

Back to the w3c spec for mouseup event (http://www.w3.org/TR/DOM-Level-3-Events/#event-type-mouseup):
1/ "A user agent must dispatch this event when a pointing device button is released over an element."
2/ Authoring Note: In some implementation environments, such as a browser, a mouseup event can be dispatched even if the pointing device has left the boundary of the user agent, e.g., if the user began a drag operation with a mouse button pressed.
Conclusion: The mouseup event that you may catch is triggered only to allow a drop outside the window. And because 1 pointer = maximum 1 drop, there are no reason that you can ever catch another event, as long as you have only 1 pointer.
For your problem: You have no way to know which button is pressed when the pointer comes back into the document, you must consider that both buttons are up by defaut, and as soon as you got the mouseup event at your document level.

Maybe try something like that
$(document).ready(function() {
var doc = $(document);
var buttons = [ false, false, false ];
function mouseDown(e) {
buttons[e.which - 1] = true;
console.log(buttons);
e.preventDefault();
alert("down")
}
function mouseUp(e) {
buttons[e.which - 1] = false;
console.log(buttons);
e.preventDefault();
alert("up")
}
doc.on("mousedown", mouseDown);
doc.on("mouseup", mouseUp);
});

in that moment, your mouse leaves the browser and you release on of the buttons, the browser will lose the focus. this is caused by the os. the browser needs to be focused to fire events.
I dont exactly know what you want to do when the keys are released, but maybe you can try out $(window).on('blur'), because i learned, that it is a big difference between body events, window events and document events. also the mouseup events are fired to that target, your mouse is targeting while releasing the button

The mouseup event is relative to where the pointer is and this is expected behaviour. If you want your button to style properly, bind the mouseleave event as well.

Related

How to identify a real click [duplicate]

I need to find a way to determine if a link has been activated via a mouse click or a keypress.
Save
The idea is that if they are using a mouse to hit the link then they can keep using the mouse to choose what they do next. But if they tabbing around the page and they tab to the Save link, then I'll open then next line for editing (the page is like a spreadsheet with each line becoming editable using ajax).
I thought the event parameter could be queried for which mouse button is pressed, but when no button is pressed the answer is 0 and that's the same as the left mouse button. They I thought I could get the keyCode from the event but that is coming back as undefined so I'm assuming a mouse event doesn't include that info.
function submitData(event, id)
{
alert("key = "+event.keyCode + " mouse button = "+event.button);
}
always returns "key = undefined mouse button = 0"
Can you help?
Could check if event.screenX and event.screenY are zero.
$('a#foo').click(function(evt) {
if (evt.screenX == 0 && evt.screenY == 0) {
window.alert('Keyboard click.');
} else {
window.alert('Mouse click.');
}
});
Demo on CodePen
I couldn't find a guarantee that it works in all browsers and all cases, but it has the benefit of not trying to detect a "click" done via the keyboard. So this solution detects "click" more reliably at the cost of detecting if it's from keyboard or mouse somewhat less reliably. If you prefer the reverse, look as the answer from #Gonzalo.
Note: One place I found using this method is Chromium
You can use event.detail
if(event.detail === 0) {
// keypress
} else {
// mouse event
}
You can create a condition with event.type
function submitData(event, id)
{
if(event.type == 'mousedown')
{
// do something
return;
}
if(event.type == 'keypress')
{
// do something else
return;
}
}
Note: You'll need to attach an event which supports both event types. With JQuery it would look something like $('a.save').bind('mousedown keypress', submitData(event, this));
The inline onClick="" will not help you as it will always pass that click event since that's how it's trapped.
EDIT: Here's a working demo to prove my case with native JavaScript: http://jsfiddle.net/AlienWebguy/HPEjt/
I used a button so it'd be easier to see the node highlighted during a tab focus, but it will work the same with any node.
You can differentiate between a click and a keyboard hit capturing and discarding the keydown event originated at the moment of the key press:
jQuery(function($) {
$("a#foo").keydown(function() {
alert("keyboard");
return false;
}).click(function() {
alert("mouse");
return false;
})
})
http://jsfiddle.net/NuP2g/
I know this is an old question but given how much time I lost looking for a working, no jquery and IE-compatible solution, I think it won't be a bad idea to put it here (where I came first).
I tested this and found it working fine :
let mouseDown = false;
element.addEventListener('mousedown', () => {
mouseDown = true;
});
element.addEventListener('mouseup', () => {
mouseDown = false;
});
element.addEventListener('focus', (event) => {
if (mouseDown) {
// keyboard
} else {
// mouse
}
});
Source link : https://www.darrenlester.com/blog/focus-only-on-tab
Wasn't able to come up with solution relying entirely on the events but you can position an anchor tag over a button and give it a tabindex of -1. This gives you a button that can be focused and engaged with keyboard enter/spacebar, as well as giving you a clickable surface that gives you an option to differentiate the two codepaths.
.button {
position: relative;
}
.anchor {
position: absolute;
top: 0;
right: 0;
bottom: 0;
left: 0;
}
<button id="button" class="button">
button
<a class="anchor" href="#example" tabindex="-1"></a>
</button>
I use the following
const isKeyboardClick = nativeEvent.detail === 0 && !nativeEvent.pointerType;
Works in evergreen browsers via detail and IE11 via pointerType. Does not work for the case where e.g. radio button <input> is wrapped by a <label> element.
Nowadays, you can make use of instanceof which even has full browser support.
function onMouseOrKeyboardSubmit(event, id) {
if (event instanceof KeyboardEvent) {
alert("Submitted via keyboard");
} else if (event instanceof MouseEvent) {
alert("Submitted via mouse");
} else {
alert("Unexpected submit event");
}
}
Handle the mouseup event.
If you get a click right afterwards, it was probably done with the mouse.

Using shift with left click for event without jQuery

My goal is to press a button and perform an action only when the shift key is also pressed. However, it doesn't even seem to recognize the shift key right now. Currently it works with only the right click but like I said, I want it to work with right click + shift.
button.addEventListener("oncontextmenu", function(e) {
document.addEventListener("keydown", function(e) {
console.log("this string won't show");
if (e.keyCode == 16) {
console.log("this string won't show either");
} else {
console.log(e.keyCode); // again it won't show
}
});
rightShiftClick(e); // this will execute perfectly.
});
The event object tells you if the shift key is pressed and there is no "on" when you are attaching the event.
button.addEventListener("contextmenu", function(e) {
console.log(e.shiftKey);
});

Why is tab keypress causing focus change also triggering keyup event?

Pressing the tab key which triggers a focus change is also received by the input receiving the focus as a keyup.
a: <input type='text'/><br/>
b: <input type='text' onkeyup='alert("wtf?")'/><br/>
http://jsfiddle.net/59SnP/
As my control also uses tab (not in the example), I would want the focus related keyup event being consumed (but I want to receive other non-focus-change related tab events). I tried to research the rationale behind the current behavior but found nothing. The question: Where is this current behavior specified (event not consumed by focus change), and what would be a cross-browser workaround to force consuming it. Thx.
You can try this. I changed your keyup event in your input :
<input type='text' onkeyup="if(!tabPressed){ alert('This is it !'); }"/>
And I added a little event handler which will raise a flag when the tab button is pressed :
var tabPressed = false;
document.addEventListener('keydown', function (e) {
if(e.keyCode == 9) {
tabPressed = true;
} else {
tabPressed = false;
}
}, false);
Based on Nathan's insight, here is a fully working example:
// First part of Nathan's HACK (set a sentinel when a focus changing tab has happened)
var tabPressed = false;
// remove this listener to break the functionality
$(document).on("keydown", function (e) {
if(e.keyCode == 9) {
tabPressed = true;
} else {
tabPressed = false;
}
});
// The listener on the client input that would kill the keyup tab event upon focus change
$("#magic").on("keyup", function(e) {
if (tabPressed && e.keyCode==9) {
tabPressed = false; // reset the sentinel
e.stopImmediatePropagation()
e.preventDefault()
}
})
And here is the second part, which is a simple skeleton of something meaningful. We disable TAB inside the input, and log it as we do with other keyups:
$("#magic").on("keydown", function(e) {
if (e.keyCode==9) {
e.preventDefault()
e.stopPropagation()
}
})
$("#magic").on("keyup", function(e) {
$(this).val($(this).val() + " " + e.keyCode)
e.stopPropagation()
e.preventDefault()
})
The HTML backing the story is as simple as:
a: <input type='text'/><br/>
b: <input type='text'/><br/>
c: <input type='text' id='magic'/><br/>
If you want to play with it, here it is on jsfiddle
NOTE: This still is not the perfect solution, the sentinel is just reset inside the control, so if a tabpress moving the focus does not activate our input, the sentinel stucks, and the first event will be swallowed.. So here is an example of wrong behaviour:
Click on input A
Press TAB (focus moves to input B, tabPressed becomes true)
Click on input C
Press TAB (it is eaten up as sentinel is true)
Press TAB (now it goes through)
Still it is slightly better to have to press TAB twice as to have something happening automatically, wo user control...

Continuous mouse click event

Is there any event generated by continuous mouse click i.e., not releasing the mouse button 1? If no, please let me know.
The mousedown event is triggered when the mouse button is pressed down. If you are looking for an event that fires repeatedly, while the button is held down, you are out of luck, but you can use the mousedown event to repeatedly perform an action, and stop when the mouseup event is triggered.
For example, you could use the setInterval function to repeatedly call a function while the mouse button is down, and then use clearInterval to stop when the mouse button is released. Here is an example (using jQuery):
var interval;
$("#elementToClick").mousedown(function() {
interval = setInterval(performWhileMouseDown, 100);
}).mouseup(function() {
clearInterval(interval);
});
function performWhileMouseDown() {
$("#output").append("<p>Mouse down</p>");
}
You can see this running in this example fiddle.
There is a JQuery plugin: LongClick
Longclick is press & hold mouse button "long click" special event for jQuery 1.4.x.
The event is triggered when the mouse button stays pressed for a (configurable) number of seconds, while the pointer is stationery.
Yes, you can do this using onmousemove= movefunction(event) :
What I did to solve this is the following:
First, create a onmousedown() event that sets a global variable to 1 when triggered.
Second, create a onmouseup() event that sets that global variable to 0 when triggered.
Then, use the onmousemove() event to trigger in the div where I want the mouse down behavior to occur but only if the global variable we set earlier is set to 1.
example on how to use onmousemove(): http://www.w3schools.com/jsref/tryit.asp?filename=tryjsref_onmousemove
Done.
There is not such event.
What you might implement to achieve this is a function that evaluates the time elapsed between the (first) mouse click ond the following mouse release.
Given a predefined range you can estabilish how long should the button be clicked before being considered valid in your logic.
According to the spec,
A click is defined as a mousedown and
mouseup over the same screen location.
The sequence of these events is:
mousedown, mouseup, click
So no, there isn't a "continuous click", because a click is a descrete event resulting from a sequence of actions.
What you probably want to do, is receive mousedown, set a timer, and if neither mouseup or mousemove occur within some time, invoke some behaviour.
There's a function I've been using to determine if an object is being dragged (if for some reason you cannot use the regular on drag event). Can't be certain that $(':focus')[0] === undefined will work for every situation, but it can be customized.
// this function will set up a mouse drag event and also check if something is being dragged
function customOnDrag(selector) {
var dragInProgress = false;
let mouseDrag = false;
let mouseDown = false;
$(selector).on('mousedown', function(event) {
mouseDrag = false;
mouseDown = true;
interval = setInterval(checkIfDraggingAnObject, 20, event); // set to check every 20 ms
}
).on('mousemove', function(event) {
if ( mouseDown ){
mouseDrag = true;
}
}
).on('mouseup', function(event) {
checkIfDraggingAnObject(event);
clearInterval(interval);
mouseDrag = false;
mouseDown = false;
}
);
// function to check if an object is being dregged:
function checkIfDraggingAnObject(event){
if ( event.type === 'mousedown' ){
if ( $(':focus')[0] === undefined || mouseDrag === false ){
// not dragging an object
dragInProgress = false;
}else{
// dragging an object
dragInProgress = true;
console.log('dragging: ');
console.log($(':focus')); // the object being dragged
};
}else if ( event.type === 'mouseup' ) {
if ( dragInProgress ){
// dropped the object
console.log('dropped: ');
console.log($(':focus')); // the dropped object
dragInProgress = false;
}else if ( mouseDrag ) {
// dragged the mouse, but no object
console.log('did not drag an object');
}else{
// did not drag the mouse
console.log('did not drag the mouse');
}
}
}
}
import java.awt.Robot;
import java.awt.event.*;
public class App {
private static final int key = InputEvent.BUTTON1_DOWN_MASK;
public static void main(String[] args) {
System.out.println("Hello, World!");
Robot robot;
while (1==1) {
try {
robot = new Robot();
robot.mousePress(key);
robot.mouseRelease(key);
// robot.mouseMove(x, y);// x,y are cordinates
// Simulate a mouse click
robot.mousePress(key);
robot.mouseRelease(key);
Thread.sleep(3000);
// Simulate a key board press
// robot.keyPress(KeyEvent.VK_A);
// robot.keyRelease(KeyEvent.VK_A);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}

JavaScript: Check if mouse button down?

Is there a way to detect if a mouse button is currently down in JavaScript?
I know about the "mousedown" event, but that's not what I need. Some time AFTER the mouse button is pressed, I want to be able to detect if it is still pressed down.
Is this possible?
Regarding Pax' solution: it doesn't work if user clicks more than one button intentionally or accidentally. Don't ask me how I know :-(.
The correct code should be like that:
var mouseDown = 0;
document.body.onmousedown = function() {
++mouseDown;
}
document.body.onmouseup = function() {
--mouseDown;
}
With the test like this:
if(mouseDown){
// crikey! isn't she a beauty?
}
If you want to know what button is pressed, be prepared to make mouseDown an array of counters and count them separately for separate buttons:
// let's pretend that a mouse doesn't have more than 9 buttons
var mouseDown = [0, 0, 0, 0, 0, 0, 0, 0, 0],
mouseDownCount = 0;
document.body.onmousedown = function(evt) {
++mouseDown[evt.button];
++mouseDownCount;
}
document.body.onmouseup = function(evt) {
--mouseDown[evt.button];
--mouseDownCount;
}
Now you can check what buttons were pressed exactly:
if(mouseDownCount){
// alright, let's lift the little bugger up!
for(var i = 0; i < mouseDown.length; ++i){
if(mouseDown[i]){
// we found it right there!
}
}
}
Now be warned that the code above would work only for standard-compliant browsers that pass you a button number starting from 0 and up. IE uses a bit mask of currently pressed buttons:
0 for "nothing is pressed"
1 for left
2 for right
4 for middle
and any combination of above, e.g., 5 for left + middle
So adjust your code accordingly! I leave it as an exercise.
And remember: IE uses a global event object called … "event".
Incidentally IE has a feature useful in your case: when other browsers send "button" only for mouse button events (onclick, onmousedown, and onmouseup), IE sends it with onmousemove too. So you can start listening for onmousemove when you need to know the button state, and check for evt.button as soon as you got it — now you know what mouse buttons were pressed:
// for IE only!
document.body.onmousemove = function(){
if(event.button){
// aha! we caught a feisty little sheila!
}
};
Of course you get nothing if she plays dead and not moving.
Relevant links:
MouseEvent's button (DOM 2)
MSDN's button
Update #1: I don't know why I carried over the document.body-style of code. It will be better to attach event handlers directly to the document.
This is an old question, and the answers here seem to mostly advocate for using mousedown and mouseup to keep track of whether a button is pressed. But as others have pointed out, mouseup will only fire when performed within the browser, which can lead to losing track of the button state.
However, MouseEvent (now) indicates which buttons are currently pushed:
For all modern browsers (including Safari v11.1+ [v11.3+ on iOS]), use MouseEvent.buttons
For Safari < 11.1 (11.3 on iOS), use MouseEvent.which (buttons will be undefined for Safari) Note: which uses different numbers from buttons for Right and Middle clicks.
When registered on document, mousemove will fire immediately as soon as the cursor reenters the browser, so if the user releases outside then the state will be updated as soon as they mouse back inside.
A simple implementation might look like:
var primaryMouseButtonDown = false;
function setPrimaryButtonState(e) {
var flags = e.buttons !== undefined ? e.buttons : e.which;
primaryMouseButtonDown = (flags & 1) === 1;
}
document.addEventListener("mousedown", setPrimaryButtonState);
document.addEventListener("mousemove", setPrimaryButtonState);
document.addEventListener("mouseup", setPrimaryButtonState);
That code tracks the state of the primary mouse button (typically the left), ignoring the state of other mouse buttons.
If more complicated scenarios are required (different buttons/multiple buttons/control keys), check out the MouseEvent docs.
I think the best approach to this is to keep your own record of the mouse button state, as follows:
var mouseDown = 0;
document.body.onmousedown = function() {
mouseDown = 1;
}
document.body.onmouseup = function() {
mouseDown = 0;
}
and then, later in your code:
if (mouseDown == 1) {
// the mouse is down, do what you have to do.
}
the solution isn't good.
one could "mousedown" on the document, then "mouseup" outside the browser, and on this case the browser would still be thinking the mouse is down.
the only good solution is using IE.event object.
I know this is an old post, but I thought the tracking of mouse button using mouse up/down felt a bit clunky, so I found an alternative that may appeal to some.
<style>
div.myDiv:active {
cursor: default;
}
</style>
<script>
function handleMove( div ) {
var style = getComputedStyle( div );
if (style.getPropertyValue('cursor') == 'default')
{
// You're down and moving here!
}
}
</script>
<div class='myDiv' onmousemove='handleMove(this);'>Click and drag me!</div>
The :active selector handles the mouse click much better than mouse up/down, you just need a way of reading that state in the onmousemove event. For that I needed to cheat and relied on the fact that the default cursor is "auto" and I just change it to "default", which is what auto selects by default.
You can use anything in the object that is returned by getComputedStyle that you can use as a flag without upsetting the look of your page e.g. border-color.
I would have liked to set my own user defined style in the :active section, but I couldn't get that to work. It would be better if it's possible.
If you're working within a complex page with existing mouse event handlers, I'd recommend handling the event on capture (instead of bubble). To do this, just set the 3rd parameter of addEventListener to true.
Additionally, you may want to check for event.which to ensure you're handling actual user interaction and not mouse events, e.g. elem.dispatchEvent(new Event('mousedown')).
var isMouseDown = false;
document.addEventListener('mousedown', function(event) {
if ( event.which ) isMouseDown = true;
}, true);
document.addEventListener('mouseup', function(event) {
if ( event.which ) isMouseDown = false;
}, true);
Add the handler to document (or window) instead of document.body is important b/c it ensures that mouseup events outside of the window are still recorded.
The following snippet will attempt to execute the "doStuff" function 2 seconds after the mouseDown event occurs in document.body. If the user lifts up the button, the mouseUp event will occur and cancel the delayed execution.
I'd advise using some method for cross-browser event attachment - setting the mousedown and mouseup properties explicitly was done to simplify the example.
function doStuff() {
// does something when mouse is down in body for longer than 2 seconds
}
var mousedownTimeout;
document.body.onmousedown = function() {
mousedownTimeout = window.setTimeout(doStuff, 2000);
}
document.body.onmouseup = function() {
window.clearTimeout(mousedownTimeout);
}
In case someone else runs into this, you can use .matches with the :active selector:
function mouseDown() {
return document.body.matches(":active");
}
Using the MouseEvent api, to check the pressed button, if any:
// Mouse buttons
document.addEventListener('mousedown', e => console.log(e.buttons))
// Keyboard keys
document.addEventListener('keydown', e => console.log(e.key))
Return:
A number representing one or more buttons. For more than one button
pressed simultaneously, the values are combined (e.g., 3 is primary +
secondary).
0 : No button or un-initialized
1 : Primary button (usually the left button)
2 : Secondary button (usually the right button)
4 : Auxilary button (usually the mouse wheel button or middle button)
8 : 4th button (typically the "Browser Back" button)
16 : 5th button (typically the "Browser Forward" button)
You can combine #Pax and my answers to also get the duration that the mouse has been down for:
var mousedownTimeout,
mousedown = 0;
document.body.onmousedown = function() {
mousedown = 0;
window.clearInterval(mousedownTimeout);
mousedownTimeout = window.setInterval(function() { mousedown += 200 }, 200);
}
document.body.onmouseup = function() {
mousedown = 0;
window.clearInterval(mousedownTimeout);
}
Then later:
if (mousedown >= 2000) {
// do something if the mousebutton has been down for at least 2 seconds
}
You need to handle the MouseDown and MouseUp and set some flag or something to track it "later down the road"... :(
Short and sweet
I'm not sure why none of the previous answers worked for me, but I came up with this solution during a eureka moment. It not only works, but it is also most elegant:
Add to body tag:
onmouseup="down=0;" onmousedown="down=1;"
Then test and execute myfunction() if down equals 1:
onmousemove="if (down==1) myfunction();"
Using jQuery, the following solution handles even the "drag off the page then release case".
$(document).mousedown(function(e) {
mouseDown = true;
}).mouseup(function(e) {
mouseDown = false;
}).mouseleave(function(e) {
mouseDown = false;
});
I don't know how it handles multiple mouse buttons.
If there were a way to start the click outside the window, then bring the mouse into the window, then this would probably not work properly there either.
As said #Jack, when mouseup happens outside of browser window, we are not aware of it...
This code (almost) worked for me:
window.addEventListener('mouseup', mouseUpHandler, false);
window.addEventListener('mousedown', mouseDownHandler, false);
Unfortunately, I won't get the mouseup event in one of those cases:
user simultaneously presses a keyboard key and a mouse button, releases mouse button outside of browser window then releases key.
user presses two mouse buttons simultaneously, releases one mouse button then the other one, both outside of browser window.
var mousedown = 0;
$(function(){
document.onmousedown = function(e){
mousedown = mousedown | getWindowStyleButton(e);
e = e || window.event;
console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
}
document.onmouseup = function(e){
mousedown = mousedown ^ getWindowStyleButton(e);
e = e || window.event;
console.log("Button: " + e.button + " Which: " + e.which + " MouseDown: " + mousedown);
}
document.oncontextmenu = function(e){
// to suppress oncontextmenu because it blocks
// a mouseup when two buttons are pressed and
// the right-mouse button is released before
// the other button.
return false;
}
});
function getWindowStyleButton(e){
var button = 0;
if (e) {
if (e.button === 0) button = 1;
else if (e.button === 1) button = 4;
else if (e.button === 2) button = 2;
}else if (window.event){
button = window.event.button;
}
return button;
}
this cross-browser version works fine for me.
Below jQuery example, when mouse is over $('.element'), color is changing depending on which mouse button is pressed.
var clicableArea = {
init: function () {
var self = this;
('.element').mouseover(function (e) {
self.handlemouseClick(e, $(this));
}).mousedown(function (e) {
self.handlemouseClick(e, $(this));
});
},
handlemouseClick: function (e, element) {
if (e.buttons === 1) {//left button
element.css('background', '#f00');
}
if (e.buttons === 2) { //right buttom
element.css('background', 'none');
}
}
};
$(document).ready(function () {
clicableArea.init();
});
Well, you can't check if it's down after the event, but you can check if it's Up... If it's up.. it means that no longer is down :P lol
So the user presses the button down (onMouseDown event) ... and after that, you check if is up (onMouseUp). While it's not up, you can do what you need.

Categories

Resources