I'm trying to detect mouse right click but the following code only detects the left click.
window.oncontextmenu = function () {
return false;
}
document.body.onclick = function (e) {
console.log("clicked", e);
}
What is wrong with my code and how can I fix this?
I'm using the latest Chrome on macOS.
window.oncontextmenu is already detecting mouse right click. What it does is disabling the default browser right click context menu for now, but you can add any additional code above it to trigger whenever right click event is performed.
window.oncontextmenu = function () {
console.log("right clicked");
return false;
}
You can try by running the code snippet and right clicking the empty space. Left clicking will not print the console.log.
EDIT: As mentioned in the comments, you could also use addEventListener to listen to contextmenu.
window.addEventListener('contextmenu', function(ev) {
ev.preventDefault();
console.log("right clicked");
});
You Can Use This Function to get right & left click event
But You Have To Use onmousedown instead using onclick
function myFunction() {
var rightclick;
if (!e) var e = window.event;
if (e.which) rightclick = (e.which == 3);
else if (e.button) rightclick = (e.button == 2);
isRclick = rightclick; // true or false
alert(isRclick);
}
Related
I want to handle mouse right-click event for my button. I wrote the following code;
mybutton.onmousedown = e => {
e.preventDefault();
const mouseEvent = {
0: () => leftClickCallback,
2: () => rightClickCallback
}
mouseEvent[ e.button ]();
}
It works fine but it doesn't prevent the browser context menu and I have to set the "oncontextmenu" event like below to prevent the browser context menu event;
mybutton.oncontextmenu = e => e.preventDefault();
I've also tried to stop propagation of mouse event like below although it didn't work:
mybutton.onmousedown = e => {
e.preventDefault();
e.stopPropagation(); // <====
const mouseEvent = {
0: () => leftClickCallback,
2: () => rightClickCallback
}
mouseEvent[ e.button ]();
}
I am wondring why I need to explicitly disable oncontextmenu event for my button.
The right mouse button click seems to fire multiple events (though it might depend on the browser) :
a MouseDown event, with event.button === 2 and/or event.which === 3,
a ContextMenu event.
It makes sense since the context menu can also be opened by a keyboard button (depending on your keyboard layout), or a macro.
What you can do is use the same callback. For example :
function preventAll(event) {
event.preventDefault();
event.stopPropagation();
}
document.getElementById('something').addEventListener('mousedown', preventAll);
document.getElementById('something').addEventListener('contextmenu', preventAll);
<button id="something">test</button>
I'm writing a desktop app using nwjs, and I want to use the right mouse button for some UI functions. This is working pretty ok right now; I am able to disable the context menu when the right click was for a UI function.
However, I am having an awful time figuring out how to not only stop right click events from opening a context menu, but also to stop them from selecting the text under the cursor.
Here is an example of what is happening (that I do not want to happen) - I am left-click dragging a handle to resize a UI view, and then while the left mouse is held down I am right clicking to cancel the resize. When the right click ends over any text, the text is selected. (Normally, a context menu would also appear.)
When handling the right mouse down event and context menu event, I am calling event.preventDefault() and returning false.
What the actual event handler code looks like (appearing in the same order as the events are spawned and handled)...
this.windowMouseDownListener = event => {
if(this.draggingResize &&
event.button === 2 && !event.ctrlKey
){
for(let view of this.area.views){
view.size = view.sizeBeforeDrag;
}
this.area.updateElementSizes();
this.draggingResize = false;
this.recentDraggingResize = true;
event.preventDefault();
event.stopPropagation();
return false;
}
};
this.windowContextMenuListener = event => {
if(this.recentDraggingResize){
event.preventDefault();
return false;
}
};
this.windowMouseUpListener = event => {
this.sizeBeforeDrag = this.size;
if(this.size <= 0.0001){
this.area.removeView(this);
}
if(this.draggingResize || this.recentDraggingResize){
this.recentDraggingResize = false;
this.draggingResize = false;
event.preventDefault();
event.stopPropagation();
return false;
}
};
How can I fix this behavior?
I want to implement a canvas minesweeper game using plain javascript. I use 2D array for my grid. For the game, I need to detect right and left mouse clicks, each of which will do different things. My research directed me towards mousedown, mouseup, contextmenu, however, my code does not seem to work, as for the right click it does the functions for both right and left click,because the mouseup event gets triggered for the right click as well. Can anyone help me understand how to distinguish between the two? I ran into examples of event.which, where left click is event.which === 0, and the right click is event.which === 2, but that works only for buttons, as far as I understood.
Here is the code.
canvas.addEventListener('mouseup', function(evt) {
let x1 = Math.floor(evt.offsetX/(canvas.height/rows));
let y1 = Math.floor(evt.offsetY/(canvas.width/cols));
draw (y1, x1); //this is my drawing functions (draws the numbers, bombs)
}, false);
canvas.addEventListener('contextmenu', function(evt) {
let j = Math.floor(evt.offsetX/(canvas.height/rows));
let i = Math.floor(evt.offsetY/(canvas.width/cols));
ctx.drawImage(flagpic, j*widthCell+5, i*widthCell+2, widthCell-9,
widthCell-5); //draws the flag where right mouse clicked
}, false);
Use click event for left click:
canvas.addEventListener('click', function(evt) { // No right click
And use contextmenu for right click: (Right click from keyboard context menu, also allowing you mouse right click)
canvas.addEventListener('contextmenu', function(evt) { // Right click
You need to call evt.preventDefault() as well for preventing the default action.
For your context, if you wanted to use mousedown or mouseup events, then you can use event.button to detect the clicked button was left:
canvas.addEventListener('mousedown', function(evt) {
if(evt.button == 0) {
// left click
}
Here's the button click values:
left button=0,
middle button=1 (if present),
right button=2
You can look on the example shown in the following link for greater details:
MouseEvent.button
<script>
var whichButton = function (e) {
// Handle different event models
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
btnCode = e.button;
switch (btnCode) {
case 0:
console.log('Left button clicked.');
break;
case 1:
console.log('Middle button clicked.');
break;
case 2:
console.log('Right button clicked.');
break;
default:
console.log('Unexpected code: ' + btnCode);
}
}
}
</script>
<button onmouseup="whichButton(event);" oncontextmenu="event.preventDefault();">
Click with mouse...
</button>
Try this might work for you
document.getElementById("mydiv").onmousedown = function(event) {
myfns(event)
};
var myfns = function(e) {
var e = e || window.event;
var btnCode;
if ('object' === typeof e) {
btnCode = e.button;
switch (btnCode) {
case 0:
console.log('Left');
break;
case 1:
console.log('Middle');
break;
case 2:
console.log('Right');
break;
}
}
}
<div id="mydiv">Click with mouse...</div>
Reference
https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button
I am creating an image gallary using owl carousel and php.there mouse click event working perfectly but when click command over keyboard having problem skip one image on prev keyup only and only first time. which code are calling after keyup function when write that code inside that function working perfectly
$(document.documentElement).keyup(function(event) {
// handle cursor keys
if (event.keyCode == 37) {
$(".prev").click();
});
var prevkey = $(".prev");
prevkey.unbind("click").click(function() {
$(".reset").click();
setTimeout(function() {
$(".printable").load(function(){
$(".owl-carousel").myfunction();
});
}, 200);
curEle = $(".item.active").parent();
//console.log(curEle);
if(curEle.find(".item").attr("data-id")==0)
{
$(this).addClass("disabled");
}
else
{
$(this).removeClass("disabled");
prevEle = curEle.prev();
console.log(prevEle);
prevEle.find(".item").addClass("active");
curEle.find(".item").removeClass("active");
prevEle.find(".printable").attr("src",prevEle.find(".printable").attr("data-src"));
carousel.trigger("owl.prev");
curEle.find(".printable").attr("src","");
}
});
Insert preventDefault() to avoid other events than yours...
$(document.documentElement).keyup(function(event) {
// handle cursor keys
event.preventDefault();
if (event.keyCode == 37) {
$(".prev").click();
}
});
EDIT check this answer if you're using IE8
try this using one will prevent a second call
$(".prev").one("click",function(){
//your stuff
});
Is there a way to check if the space bar and at the same time track what direction the mouse is moving and how far etc.
Point of this is that I want to replicate how Photoshop scrolls when you hold the space bar, left mouse button and you move the mouse, but without having to hold down the left mouse button.
You can use keydown() and keyup() to track if the space bar is pressed or not and look at that state in your mousemove() event handler. For example:
var space = false;
$(function() {
$(document).keyup(function(evt) {
if (evt.keyCode == 32) {
space = false;
}
}).keydown(function(evt) {
if (evt.keyCode == 32) {
space = true;
console.log('space')
}
});
});
And then your mousemove() handler can see if it's pressed or not.
you will probably have to be watching for the keydown event, check to see that it's the spacebar, set a variable saying it's down, unset it when the keyup event is seen.
so, then you would look for mouse movements when that variable was set indicating the spacebar was pressed.
This is my solution:
var allowed = true;
$(document).ready(
function () {
$(document).bind('keydown', 'space', function () {
if (!allowed) return;
allowed = false;
$('#viewport').
dragscrollable();
});
$(document).bind('keyup', 'space', function () {
allowed = true;
$('#base').off('mousedown');
return false;
});
});
Works with jQuery and the Dragscrollable Plugin.