JavaScript: Check if mouse button down?
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.
Check if mouse button is down on a button/picture and keep executing a function after every few seconds till the button is pressed?
This should work for you:
var timerId = 0;
function onmousedown(ev) {
console.log("Do something"); //first call right after mouse down
timerId = setInterval(function () {
console.log("Do something");
}, 2000);
}
function onmouseup(ev) {
clearInterval(timerId);
}
var obj = document.getElementById("foo");
obj.addEventListener("mousedown", onmousedown);
obj.addEventListener("mouseup", onmouseup);
fiddle: https://jsfiddle.net/kLnjh9zd/
Check if mousedown with an if statement?
The easiest way I can think of is to bind mousedown
and mouseup
event listeners to the document
and update a global variable accordingly. In the mouseout
event of your element you can check the state of that variable and act as appropriate. (Note: this assumes that you don't care whether or not the mouse was pressed down while over the div
or not... you'll have to clarify your question around that).
var down = false;
$(document).mousedown(function() {
down = true;
}).mouseup(function() {
down = false;
});
$("#example").mouseout(function() {
if(down) {
console.log("down");
}
else {
console.log("up");
}
});
Here's a working example of the above.
Javascript check if left mouse button is clicked
This might help you,
$(document).ready(function() {
$(document).mousedown(function(e) {
if (e.which === 1) {
alert("left");
}else if(e.which === 3){
alert("right");
}
});
});
How to detect if mouse button is held down for a certain amount of time after click
There are a couple of keys that needs to be considered for this to work properly:
- An element can only detect mouse events for itself when the mouse is over it. For mouseup to work properly it has to be monitored "globally" (on window or document), and the button status tracked.
- A status for type the long-press must be tracked and respected in all stages. For example: if long press, make sure mouseup eventually respect the new status and is itself overridden (or you will get a mouseup on top of a longpress). If you do want the mouseup in any casejust ignore this point of course.
- Functionality for multiple elements (see comment below)
You can make the handlers generic by referencing this
inside the handler code. This way you can attach it to any element. The global handler for mouseup is only added once and will use a tracked target to distinguish which element caused the mousedown. The timer invoked code will have the element context bound (bind()
) so we can use the generic longpress handler addressing the source element as well (see demo below).
Example
var d = document.querySelectorAll("div"), isDown = false, isLong = false, target, // which element was clicked longTID; // so we can cancel timer
// add listener for elementsd[0].addEventListener("mousedown", handleMouseDown);d[1].addEventListener("mousedown", handleMouseDown);d[2].addEventListener("mousedown", handleMouseDown);
// mouseup need to be monitored on a "global" element or we might miss it if// we move outside the original element.window.addEventListener("mouseup", handleMouseUp);
function handleMouseDown() { this.innerHTML = "Mouse down..."; isDown = true; // button status (any button here) isLong = false; // longpress status reset target = this; // store this as target element clearTimeout(longTID); // clear any running timers longTID = setTimeout(longPress.bind(this), 1500); // create a new timer for this click};
function handleMouseUp(e) { if (isDown && isLong) { // if a long press, cancel isDown = false; // clear in any case e.preventDefault(); // and ignore this event return } if (isDown) { // if we came from down status: clearTimeout(longTID); // clear timer to avoid false longpress isDown = false; target.innerHTML = "Normal up"; // for clicked element target = null; }};
function longPress() { isLong = true; this.innerHTML = "Long press"; // throw custom event or call code for long press}
div {background:#ffe;border:2px solid #000; width:200px;height:180px; font:bold 16px sans-serif;display:inline-block}
<div>Click and hold me...</div><div>Click and hold me...</div><div>Click and hold me...</div>
Related Topics
JavaScript Function Order: Why Does It Matter
Referencing Another Schema in Mongoose
How to Shuffle the Characters in a String in JavaScript
Secure Random Numbers in JavaScript
Best Practice for Using Window.Onload
Is There Any Difference Between Declared and Defined Variable
How to Remove Spaces from a String Using JavaScript
Regex for Match/Replacing JavaScript Comments (Both Multiline and Inline)
Chrome Extension: Port Error: Could Not Establish Connection. Receiving End Does Not Exist
Convert Js Object to Form Data
Leaflet Drawing Tiles Disjointly
Why Were Es5 Object Methods Not Added to Object.Prototype
Can You Force Vue.Js to Reload/Re-Render
Extending Built-In Natives in Es6 with Babel
How to Test If a String Is JSON or Not
How to Check Whether <Ng-Content> Is Empty? (In Angular 2+ Till Now)