I've been working all day on this with no progress. Anyways, I've got to build a SIMPLE JavaScript program, since we are only in the beginning phase, basically there should be a button and if I press it with the LEFT mouse button, it should alert("LEFT"), this part is easy because I can use onClick, but I should also check if I pressed the button with the RIGHT mouse button, in that case it should alert("RIGHT"). My struggle comes from the fact that it's easy to check the left button, but how do you actually do it with the right button? It might be a simple problem, but I don't seem to find a correct answer. Thank you in advance.
Simply check the event.button code
0 === left
2 === right
document.querySelector(buttonSelector).addEventListener('mousedown', (e) => {
if(e.button === 0){
alert('Left')
}else if(e.button === 2){
alert('Right')
}
});
I would add in this 'contextmenu' piece if you don't already have it to prevent the right click context menu from popping up.
document.getElementById('buttonID').addEventListener('mousedown', (e) => {
if (e.button === 0) {
console.log('Left')
} else if (e.button === 2) {
console.log('Right')
}
});
document.getElementById('buttonID').addEventListener("contextmenu", (e) => {
e.preventDefault();
return false;
});
Related
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.
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);
});
I know there are many questions asking how to prevent the autoscrolling mode that Firefox activates when a page is bigger than the viewport and you press the middle mouse button.
But what I actually need is just being able to detect the mouseup event, when autoscrolling is active. The event just doesn't seem to propagate, so I don't know when (and more important where) the mouse button is released.
I could also settle for detecting when the autoscrolling mode is gone and the mouse usage is back to normal.
I've prepared a Plunk to play with. When it starts, middle click anywhere and the text in the box will update. If you press the button, more content is added to the page: middle click will activate autoscrolling and the mouseup event is lost forever.
Link
Does this give a result?
$(selector).live('mouseup', function(e) {
if(e.which == 1) {
alert("left");
}if(e.which == 3) {
alert("right button");
}else if(e.which == 2) {
alert("middle button");
}
e.preventDefault();
});
$(document).ready(function(){
$("your id").on('mousedown', function(e) {
if( (e.which == 1) ) {
alert("left button");
} else if( (e.which == 3) ) {
alert("right button");
} else if( (e.which == 2) ) {
alert("middle button");
}
e.preventDefault();
}).on('contextmenu', function(e){
e.preventDefault();
});
});
http://jsfiddle.net/p49nF/
Hope,this helps.!!!
Got it.
Even tho' Pieter's answer is not correct, it gave me the correct idea.
For some reason if you preventDefault() in the mousedown handler, the mouseup one starts working.
$(document)
.on("mousedown", function(e) {
if (e.which !== 2) return;
$("#h").text("MouseDown");
e.preventDefault();
}).on("mouseup", function(e) {
if (e.which !== 2) return;
$("#h").text("MouseUp");
});
Plunk with the solution
My goal: Press and HOLD space key while an effect occurs (to simulate a fingerprint scan). If user releases key before effect finishes, I want to display a confirm message. The keydown part works fine and proceeds to function "process", but no error message is displayed on keyup if it is released before the effect finishes. This is what I have...
var active = false;
$(document).one("keydown", function(e) {
if ((e.keyCode == 32) && (active == false)) {
active = true;
$(".panel_1").slideDown(5000, function() {
active = false;
$(".panel_1").slideUp(2000, function() {process(); })
});
}
});
$(document).one("keyup",function(e) {
if ((e.keyCode == 32) && (active == true)) {
var r=confirm("Oops! You must HOLD down the space key until scan is complete. Press OK to try again, or Cancel to return to homepage.");
if (r==true) {
reset();
}
else {
window.location.replace("home.html");
}
}
});
Verify that you are releasing the key during the first slideDown animation. According to your code, once it starts to slide up your active gets set to false and then makes it so the keyup event will not trigger.
Also as a side note I'd recommend using triple = in JavaScript.
Your code seems to work here: http://jsfiddle.net/D52eq/ but note that the confirmation message occurs only if the space bar is released during the .slideDown() phase of the effect - you're setting active = false; before the .slideUp() call.
If you want the confirmation if the space bar is released before completion of the entire animation and process() call then try this:
$(document).one("keydown", function(e) {
if ((e.keyCode == 32) && (!active)) {
active = true;
$(".panel_1").slideDown(5000).slideUp(2000, function() {
process();
active = false;
})
}
});
Note that then you can just chain the .slideDown() and .slideUp(), you don't need to supply a callback function to .slideDown(). Also I've replaced active == false with !active.
Demo: http://jsfiddle.net/D52eq/1/
I’m working with basic HTML <input type="text"/> text field with a numeric value.
I’m adding JavaScript event keyup to see when user presses arrow up key (e.which == 38) – then I increment the numeric value.
The code works well, but there’s one thing that bugs me. Both Safari/Mac and Firefox/Mac move cursor at the very beginning when I’m pressing the arrow up key. This is a default behavior for every <input type="text"/> text field as far as I know and it makes sense.
But this creates not a very aesthetic effect of cursor jumping back and forward (after value was altered).
The jump at the beginning happens on keydown but even with this knowledge I’m not able to prevent it from occuring. I tried the following:
input.addEventListener('keydown', function(e) {
e.preventDefault();
}, false);
Putting e.preventDefault() in keyup event doesn’t help either.
Is there any way to prevent cursor from moving?
To preserve cursor position, backup input.selectionStart before changing value.
The problem is that WebKit reacts to keydown and Opera prefers keypress, so there's kludge: both are handled and throttled.
var ignoreKey = false;
var handler = function(e)
{
if (ignoreKey)
{
e.preventDefault();
return;
}
if (e.keyCode == 38 || e.keyCode == 40)
{
var pos = this.selectionStart;
this.value = (e.keyCode == 38?1:-1)+parseInt(this.value,10);
this.selectionStart = pos; this.selectionEnd = pos;
ignoreKey = true; setTimeout(function(){ignoreKey=false},1);
e.preventDefault();
}
};
input.addEventListener('keydown',handler,false);
input.addEventListener('keypress',handler,false);
I found that a better solution is just to return false; to prevent the default arrow key behavior:
input.addEventListener("keydown", function(e) {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') return false;
}, false);
Actually, there is a better and simpler method to do this job.
$('input').bind('keydown', function(e){
if(e.keyCode == '38' || e.keyCode == '40'){
e.preventDefault();
}
});
Yes, it is so easy!
In my case (react) helped:
onKeyDown = {
(e) => {
if (e.key === 'ArrowUp' || e.key === 'ArrowDown') e.preventDefault();
}
}
and onKeyUp was fully functional
I tested the code and it seems that it cancels the event but if you don't press the arrow for very short time - it fires keypress event and that event actually moves cursor. Just use preventDefault() also in keypress event handler and it should be fine.
Probably not. You should instead seek for a solution to move the cursor back to the end of the field where it was. The effect would be the same for the user since it is too quick to be perceived by a human.
I googled some and found this piece of code. I can't test it now and it is said to not to work on IE 6.
textBox.setSelectionRange(textBox.value.length, textBox.value.length);