How to detect right click + left click - javascript

I am building a game
And I need to do something when the user clicks on the right mouse button, holds it and then presses the left button
How can I detect this behaviour?

JSfiddle: https://jsfiddle.net/mkarajohn/pd725ch6/5/
var rightMouseClicked = false;
function handleMouseDown(e) {
//e.button describes the mouse button that was clicked
// 0 is left, 1 is middle, 2 is right
if (e.button === 2) {
rightMouseClicked = true;
} else if (e.button === 0) {
//Do something if left button was clicked and right button is still pressed
if (rightMouseClicked) {
console.log('hello');
//code
}
}
console.log(rightMouseClicked);
}
function handleMouseUp(e) {
if (e.button === 2) {
rightMouseClicked = false;
}
console.log(rightMouseClicked);
}
document.addEventListener('mousedown', handleMouseDown);
document.addEventListener('mouseup', handleMouseUp);
document.addEventListener('contextmenu', function(e) {
e.preventDefault();
});

Use MouseEvent.buttons in your event handler.
<element>.addEventListener("mousedown", function(event){
if ((event.buttons & 3) === 3){
//Do something here
}
}, true);
It is kinda recent though, you may want to implement fallback method, recording state of mouse buttons.

You can try this one.
window.oncontextmenu = function () {
showCustomMenu();
return false; // cancel default menu
}
on right click every browser has default menu for refreshing page, printing, saving and lot more but you can try this one and may be it will prevent default action and add your custom.
please write down answer if it will help you.

for right click use oncontextmenu and for left just set up click , just disable their default behaviours if you want too,
ex:
var left = 0,
right = 0;
document.onclick = function() {
console.log(++left);
return false;
};
document.oncontextmenu = function() {
console.log(++right);
return false;
};

Hie
check below code
<!doctype html>
<html lang="en">
<head>
<input type='button' value='Click Me!!!' id='btnClick'/>
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<script>
$(document).ready(function() {
$('#btnClick').mousedown(function(event){
switch (event.which) {
case 1:
alert('Left mouse button pressed');
break;
case 2:
alert('Middle mouse button pressed');
break;
case 3:
alert('Right mouse button pressed');
break;
default:
break;
}
});
});
</script>
</body>
</html>
For more reference refer
http://www.jquerybyexample.net/2011/04/find-which-mouse-button-clicked-using.html

Try
var hold=false;
function check(e) {
if(e.button==2) hold=true;
if(e.button==0 && hold) console.log('action');
}
function release(e) {
if(e.button==2) hold=false;
}
function noContext(e) { e.preventDefault(); }
.box { width: 100px; height: 100px; border: 1px solid black;}
Hold right mouse button and press left (on sqare)
<div class="box"
onmousedown="check(event)"
onmouseup="release(event)"
oncontextmenu="noContext(event)"
></div>

Related

Disable mouse scroll middle click event with jQuery

I wrote the below code for disabling the scroll in the mouse while it is clicked.
but my code does not work an when I click with the scroll of my mouse it opens my link.
Here is my code :
$('a').on('mousedown', function(e) {
if (e.which === 2) {
console.log('Disabled');
return false;
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
click here
You have to use auxclick in order to disable this feature. Replace your 'click' with 'auxclick', and add e.preventDefault(), it will work, tested in chrome and FF
$('a').on('auxclick', function(e) {
if (e.which === 2) {
e.preventDefault();
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js"></script>
click here
You can use event.preventDefault() to cancel a action
document.onmousedown= function (e) {
if( e.which == 2 ) {
e.preventDefault();
alert("middle button pressed, dont open");
}
}
click here
try the code below, thanks :
click here
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.0/jquery.min.js">
</script>
<script>
var el = document.getElementById('link_click');
el.onmousedown = mouse_down;
function mouse_down() {
alert('mouse_down() called');
return false;
}
</script>

How can I exit a click function or prevent the function from triggering until a condition is met

Goal:
I want to be able to add comments onto images and use their X,Y coordinates to save the comment and display for later.
Expected Result:
I want a user to click on a "New Comment" button which enables "Comment Mode" and displays a form. If a user clicks away from the form, I want the form to hide and "Comment Mode" to become disabled until the user clicks "New Comment" again. If "New Comment" is pressed again, repeat the above.
Actual Result:
The snippet of code currently allows a user to click "New Comment". Once clicked the commentMode() function is triggered and listens for a click on the #imageWrapper. If the user clicks away, the form is hidden - but when I press "New Comment" again, the form remains hidden.
function commentMode() {
imageWrapper.toggleClass('new-comment-pointer'); // changes cursor to show its active
imageWrapper.click(function(e) { // on clicking the image
newComment = !newComment; // newComment is true
console.log(newComment);
if(newComment) { // if newComment is true, show the form near the click
getCoordinates(e, $('#imageWrapper'));
form.show().css({'left': formX, 'top': formY});
form.find('textarea').focus();
form.find('#xAxis').val(x); // x is from the getCoordinates
form.find('#yAxis').val(y); // y is from the getCoordinates
} else { // if newComment is false, hide the form and turn stop imageWrapper.click
form.hide();
imageWrapper.removeClass('new-comment-pointer');
newComment = !newComment;
return; //stop listening for click
}
return;
});
}
https://codepen.io/lachiekimber/pen/YzzPEqw
I do not know why everybody make it complicated.
First give the form and the button a id. Then define a default form css class which is hidden.Define another ones which makes it visible some kind of:
<style>
.invisible {
display:none;
}
.visible {
display:block !important;
}
</style>
Now we add a document listener which make things more simple instead fiddeling on whatever event...
document.addEventListener(" click ", function(event) {
//try to get a id even when the event element has not
// directly a id but maybee his parent the form
try {
var id = event.target.id;
if (id === "") {
for (i = 0; i < event.path.length; i++) {
id = event.path[i].id;
if (id !== "") {
if (id === "formid") {
break;
}
}
}
} catch(ex){
console.log(ex);
return;
}
var form=document.getElementById("formid");
switch(id){
case "showcommehtbuttonid":
case "formid":
form.classList.add("visible");
break;
default:
form.classList.remove("visible");
}
}
The toggle state has a disadvantage in your case - complicate to handle. Works best by a simple id and button. There is no doubt about then. Adding and removing handlers also makes no real sense. Either the user clicks on the form or the button and the form becomes visible. Or he clicks something else. In this case no id or the "wrong" id will be chosen. In this case the default switch rule make the form invisible. The thing is untested and might need some minor tweaks. And best - in the event handler you can now also add very simple more actions.
As #Davo mentioned in the comments, I attempted to refactor the code. I started by cleaning up the code into functions and not nesting click events. Whilst refactoring, I used console.log's to help me identify when the commentMode was active - then triggered the showForm() or hideForm() functions. For a working example: https://codepen.io/lachiekimber/pen/bGGNYmK
$(function () {
var imageWrapper = $('#imageWrapper');
var form = $('.new-comment');
var x, y, formX, formY;
var newComment = true;
var commentMode = false;
$('#newComment').click(function() {
imageWrapper.toggleClass('new-comment-pointer');
commentMode = !commentMode;
//console.log('newComment');
});
$('#imageWrapper').click(function(e) {
if(commentMode) {
//console.log('commentMode: true');
showForm(e);
} else {
//console.log('commentMode: false');
hideForm();
}
});
function showForm(e) {
getCoordinates(e, imageWrapper);
form.show().css({'left': formX, 'top': formY});
form.find('textarea').focus();
form.find('#xAxis').val(x); // x is from the getCoordinates
form.find('#yAxis').val(y); // y is from the getCoordinates
}
function hideForm() {
form.hide();
}
function getCoordinates(e, image) {
var offset = image.offset();
x = e.pageX - offset.left;
y = e.pageY - offset.top;
formX = x + 50;
formY = y + 20;
}
});
Working and tested :) ! Ok we could work on the page style quite a bit but :d
Look how simple the whole page looks also. I do not have to fight with jquery for this little task :) I set also the autofocus just by plain html.
<!DOCTYPE HTML>
<html>
<head>
<title>Untitled</title>
<style>
.invisible {
display: none;
border: 1px solid red;
}
.visible {
display: block !important;
}
</style>
</head>
<body>
<form id="formid" class="invisible">
<h1>Form</h1>
<input type="text" name="size" autofocus>
</form>
<hr>
<input type="button" value="click" id="showcommentbuttonid">
<script>
document.addEventListener("click", function(event) {
try {
var id = event.target.id;
if (id === "") {
for (i = 0; i < event.path.length; i++)
{
id = event.path[i].id;
if (id !== "") {
if (id === "formid") {
break;
}
}
}
}
} catch (ex) {
console.log(ex);
return;
}
var form = document.getElementById("formid");
switch (id) {
case "showcommentbuttonid":
case "formid":
form.classList.add("visible");
break;
default:
form.classList.remove("visible");
}
}
)
</script>
</body>
</html>

Javascript to trigger one function only if two events are both true

Say I want to activate myFunction only if the user has pressed the paragraph with a key and clicks on it. In the case below, the function will get triggered if any of the events is true.
<p id="p1" onClick="myFunction()" onKeyDown="myFunction()">
Text awaiting to be colored in red</p>
<script>
function myFunction(){
document.getElementById("p1").style.color = "red";
}
</script>
You need one extra variable isKeyDown, and isKeyDown should be set to true on keydown, and set to false on keyup.
And than in click callback check is isKeyDown true, call myFunction.
An example of how you could do it. This works with Enter and normally clicking it. Really you don't need to make p focus but I thought it was neat, even though you can still handle the key events from the document and since the click only registers on p there's nothing to worry about.
var p = document.getElementById('p1');
p.addEventListener('mousedown', function(e) {
p.clicked = true;
checkEvents(p);
});
p.addEventListener('mouseup', function(e) {
p.clicked = false;
});
p.addEventListener('keydown', function(e) {
if (e.keyCode === 13) {
p.enterDown = true;
}
});
p.addEventListener('keyup', function(e) {
checkEvents(p);
if (e.keyCode === 13) {
p.enterDown = false;
}
});
function checkEvents(el){
if(el.enterDown && el.clicked){
el.style.backgroundColor = 'red';
}
}
p:focus {
outline: none;
}
<p id="p1" tabindex='0'>
Text awaiting to be colored in red</p>
You'll need to breakdown into two methods. First is keystrokes->click and then click->keystrokes. I'm not sure if this is achievable on pure/vanilla javascaript. But on jquery it goes something like:
$('#p1' ).keydown(function() {
if($('#p1').click()) {
document.getElementById("p1").style.color = "red";
}
});
$('#p1')click(function () {
if($('#p1').keydown()) {
document.getElementById("p1").style.color = "red";
}
});

How to change mouse left click and right click option?

I have some set of HTML files named in sequence. Is it possible to assign mouse right click to next html page and mouse left click to previous html page and how to do this?
This is how we handles the mouse click..
$('#element').mousedown(function(event) {
switch (event.which) {
case 1:
alert('Left mouse button pressed');
//code to navigate to left page
break;
case 2:
alert('Right mouse button pressed');
//code to navigate to right page
break;
default:
alert('Mouse is not good');
}
});
$(function(){
$(document).mousedown(function(event) {
switch (event.which) {
case 1:
window.location.href = "http://stackoverflow.com" // here url prev. page
break;
case 3:
window.location.href = "http://www.google.com" // here url next. page
break;
default:
break;
}
});
})
And don't forgot add jquery library.
You can also do this with some simple Javascript.
<script type='text/javascript'>
function right(e){
//Write code to move you to next HTML page
}
<canvas style='width: 100px; height: 100px; border: 1px solid #000000;' oncontextmenu='right(event); return false;'>
//Everything between here's right click is overridden.
</canvas>
This is the traditional way to override left and right clicks. In the code I'm preventing event propagation of the right-click also so the context menu won't display.
JSFiddle
window.onclick = leftClick
window.oncontextmenu = function (event) {
event = event || window.event;
if (event.stopPropagation)
event.stopPropagation();
rightClick();
return false;
}
function leftClick(event) {
alert('left click');
window.location.href = "http://www.google.com";
}
function rightClick(event) {
alert('right click');
window.location.href = "http://images.google.com";
}

How to distinguish between left and right mouse click with jQuery

How do you obtain the clicked mouse button using jQuery?
$('div').bind('click', function(){
alert('clicked');
});
this is triggered by both right and left click, what is the way of being able to catch right mouse click? I'd be happy if something like below exists:
$('div').bind('rightclick', function(){
alert('right mouse button is pressed');
});
As of jQuery version 1.1.3, event.which normalizes event.keyCode and event.charCode so you don't have to worry about browser compatibility issues. Documentation on event.which
event.which will give 1, 2 or 3 for left, middle and right mouse buttons respectively so:
$('#element').mousedown(function(event) {
switch (event.which) {
case 1:
alert('Left Mouse button pressed.');
break;
case 2:
alert('Middle Mouse button pressed.');
break;
case 3:
alert('Right Mouse button pressed.');
break;
default:
alert('You have a strange Mouse!');
}
});
Edit: I changed it to work for dynamically added elements using .on() in jQuery 1.7 or above:
$(document).on("contextmenu", ".element", function(e){
alert('Context Menu event has fired!');
return false;
});
Demo: jsfiddle.net/Kn9s7/5
[Start of original post] This is what worked for me:
$('.element').bind("contextmenu",function(e){
alert('Context Menu event has fired!');
return false;
});
In case you are into multiple solutions ^^
Edit: Tim Down brings up a good point that it's not always going to be a right-click that fires the contextmenu event, but also when the context menu key is pressed (which is arguably a replacement for a right-click)
You can easily tell which mouse button was pressed by checking the which property of the event object on mouse events:
/*
1 = Left mouse button
2 = Centre mouse button
3 = Right mouse button
*/
$([selector]).mousedown(function(e) {
if (e.which === 3) {
/* Right mouse button was clicked! */
}
});
You can also bind to contextmenu and return false:
$('selector').bind('contextmenu', function(e){
e.preventDefault();
//code
return false;
});
Demo: http://jsfiddle.net/maniator/WS9S2/
Or you can make a quick plugin that does the same:
(function( $ ) {
$.fn.rightClick = function(method) {
$(this).bind('contextmenu rightclick', function(e){
e.preventDefault();
method();
return false;
});
};
})( jQuery );
Demo: http://jsfiddle.net/maniator/WS9S2/2/
Using .on(...) jQuery >= 1.7:
$(document).on("contextmenu", "selector", function(e){
e.preventDefault();
//code
return false;
}); //does not have to use `document`, it could be any container element.
Demo: http://jsfiddle.net/maniator/WS9S2/283/
$("#element").live('click', function(e) {
if( (!$.browser.msie && e.button == 0) || ($.browser.msie && e.button == 1) ) {
alert("Left Button");
}
else if(e.button == 2){
alert("Right Button");
}
});
Update for the current state of the things:
var $log = $("div.log");
$("div.target").on("mousedown", function() {
$log.text("Which: " + event.which);
if (event.which === 1) {
$(this).removeClass("right middle").addClass("left");
} else if (event.which === 2) {
$(this).removeClass("left right").addClass("middle");
} else if (event.which === 3) {
$(this).removeClass("left middle").addClass("right");
}
});
div.target {
border: 1px solid blue;
height: 100px;
width: 100px;
}
div.target.left {
background-color: #0faf3d;
}
div.target.right {
background-color: #f093df;
}
div.target.middle {
background-color: #00afd3;
}
div.log {
text-align: left;
color: #f00;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="target"></div>
<div class="log"></div>
$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};
$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});
http://jsfiddle.net/SRX3y/8/
There are a lot of very good answers, but I just want to touch on one major difference between IE9 and IE < 9 when using event.button.
According to the old Microsoft specification for event.button the codes differ from the ones used by W3C. W3C considers only 3 cases:
Left mouse button is clicked - event.button === 1
Right mouse button is clicked - event.button === 3
Middle mouse button is clicked - event.button === 2
In older Internet Explorers however Microsoft are flipping a bit for the pressed button and there are 8 cases:
No button is clicked - event.button === 0 or 000
Left button is clicked - event.button === 1 or 001
Right button is clicked - event.button === 2 or 010
Left and right buttons are clicked - event.button === 3 or 011
Middle button is clicked - event.button === 4 or 100
Middle and left buttons are clicked - event.button === 5 or 101
Middle and right buttons are clicked - event.button === 6 or 110
All 3 buttons are clicked - event.button === 7 or 111
Despite the fact that this is theoretically how it should work, no Internet Explorer has ever supported the cases of two or three buttons simultaneously pressed. I am mentioning it because the W3C standard cannot even theoretically support this.
It seems to me that a slight adaptation of TheVillageIdiot's answer would be cleaner:
$('#element').bind('click', function(e) {
if (e.button == 2) {
alert("Right click");
}
else {
alert("Some other click");
}
}
EDIT: JQuery provides an e.which attribute, returning 1, 2, 3 for left, middle, and right click respectively. So you could also use if (e.which == 3) { alert("right click"); }
See also: answers to "Triggering onclick event using middle click"
event.which === 1 ensures it's a left-click (when using jQuery).
But you should also think about modifier keys: ctrlcmdshiftalt
If you're only interested in catching simple, unmodified left-clicks, you can do something like this:
var isSimpleClick = function (event) {
return !(
event.which !== 1 || // not a left click
event.metaKey || // "open link in new tab" (mac)
event.ctrlKey || // "open link in new tab" (windows/linux)
event.shiftKey || // "open link in new window"
event.altKey // "save link as"
);
};
$('a').on('click', function (event) {
if (isSimpleClick(event)) {
event.preventDefault();
// do something...
}
});
To those who are wondering if they should or not use event.which in vanilla JS or Angular : It's now deprecated so prefer using event.buttons instead.
Note : With this method and (mousedown) event:
left click press is associated to 1
right click press is associated to 2
scroll button press is associated with 4
and (mouseup) event will NOT return the same numbers but 0 instead.
Source : https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/buttons
there is also a way, to do it without JQuery!
check out this:
document.addEventListener("mousedown", function(evt) {
switch(evt.buttons) {
case 1: // left mouse
case 2: // right mouse
case 3: // middle mouse <- I didn't tested that, I just got a touchpad
}
});
<!DOCTYPE html>
<html>
<head>
<title>JS Mouse Events - Button Demo</title>
</head>
<body>
<button id="btn">Click me with any mouse button: left, right, middle, ...</button>
<p id="message"></p>
<script>
let btn = document.querySelector('#btn');
// disable context menu when right-mouse clicked
btn.addEventListener('contextmenu', (e) => {
e.preventDefault();
});
// show the mouse event message
btn.addEventListener('mouseup', (e) => {
let msg = document.querySelector('#message');
switch (e.button) {
case 0:
msg.textContent = 'Left mouse button clicked.';
break;
case 1:
msg.textContent = 'Middle mouse button clicked.';
break;
case 2:
msg.textContent = 'Right mouse button clicked.';
break;
default:
msg.textContent = `Unknown mouse button code: ${event.button}`;
}
});
</script>
</body>
</html>
If you are looking for "Better Javascript Mouse Events" which allow for
left mousedown
middle mousedown
right mousedown
left mouseup
middle mouseup
right mouseup
left click
middle click
right click
mousewheel up
mousewheel down
Have a look at this cross browser normal javascript which triggers the above events, and removes the headache work. Just copy and paste it into the head of your script, or include it in a file in the <head> of your document. Then bind your events, refer to the next code block below which shows a jquery example of capturing the events and firing the functions assigned to them, though this works with normal javascript binding as well.
If your interested in seeing it work, have a look at the jsFiddle: https://jsfiddle.net/BNefn/
/**
Better Javascript Mouse Events
Author: Casey Childers
**/
(function(){
// use addEvent cross-browser shim: https://gist.github.com/dciccale/5394590/
var addEvent = function(a,b,c){try{a.addEventListener(b,c,!1)}catch(d){a.attachEvent('on'+b,c)}};
/* This function detects what mouse button was used, left, right, middle, or middle scroll either direction */
function GetMouseButton(e) {
e = window.event || e; // Normalize event variable
var button = '';
if (e.type == 'mousedown' || e.type == 'click' || e.type == 'contextmenu' || e.type == 'mouseup') {
if (e.which == null) {
button = (e.button < 2) ? "left" : ((e.button == 4) ? "middle" : "right");
} else {
button = (e.which < 2) ? "left" : ((e.which == 2) ? "middle" : "right");
}
} else {
var direction = e.detail ? e.detail * (-120) : e.wheelDelta;
switch (direction) {
case 120:
case 240:
case 360:
button = "up";
break;
case -120:
case -240:
case -360:
button = "down";
break;
}
}
var type = e.type
if(e.type == 'contextmenu') {type = "click";}
if(e.type == 'DOMMouseScroll') {type = "mousewheel";}
switch(button) {
case 'contextmenu':
case 'left':
case 'middle':
case 'up':
case 'down':
case 'right':
if (document.createEvent) {
event = new Event(type+':'+button);
e.target.dispatchEvent(event);
} else {
event = document.createEventObject();
e.target.fireEvent('on'+type+':'+button, event);
}
break;
}
}
addEvent(window, 'mousedown', GetMouseButton);
addEvent(window, 'mouseup', GetMouseButton);
addEvent(window, 'click', GetMouseButton);
addEvent(window, 'contextmenu', GetMouseButton);
/* One of FireFox's browser versions doesn't recognize mousewheel, we account for that in this line */
var MouseWheelEvent = (/Firefox/i.test(navigator.userAgent)) ? "DOMMouseScroll" : "mousewheel";
addEvent(window, MouseWheelEvent, GetMouseButton);
})();
Better Mouse Click Events Example (uses jquery for simplicity, but the above will work cross browser and fire the same event names, IE uses on before the names)
<div id="Test"></div>
<script type="text/javascript">
$('#Test').on('mouseup',function(e){$(this).append(e.type+'<br />');})
.on('mouseup:left',function(e){$(this).append(e.type+'<br />');})
.on('mouseup:middle',function(e){$(this).append(e.type+'<br />');})
.on('mouseup:right',function(e){$(this).append(e.type+'<br />');})
.on('click',function(e){$(this).append(e.type+'<br />');})
.on('click:left',function(e){$(this).append(e.type+'<br />');})
.on('click:middle',function(e){$(this).append(e.type+'<br />');})
.on('click:right',function(e){$(this).append(e.type+'<br />');})
.on('mousedown',function(e){$(this).html('').append(e.type+'<br />');})
.on('mousedown:left',function(e){$(this).append(e.type+'<br />');})
.on('mousedown:middle',function(e){$(this).append(e.type+'<br />');})
.on('mousedown:right',function(e){$(this).append(e.type+'<br />');})
.on('mousewheel',function(e){$(this).append(e.type+'<br />');})
.on('mousewheel:up',function(e){$(this).append(e.type+'<br />');})
.on('mousewheel:down',function(e){$(this).append(e.type+'<br />');})
;
</script>
And for those who are in need of the minified version...
!function(){function e(e){e=window.event||e;var t="";if("mousedown"==e.type||"click"==e.type||"contextmenu"==e.type||"mouseup"==e.type)t=null==e.which?e.button<2?"left":4==e.button?"middle":"right":e.which<2?"left":2==e.which?"middle":"right";else{var n=e.detail?-120*e.detail:e.wheelDelta;switch(n){case 120:case 240:case 360:t="up";break;case-120:case-240:case-360:t="down"}}var c=e.type;switch("contextmenu"==e.type&&(c="click"),"DOMMouseScroll"==e.type&&(c="mousewheel"),t){case"contextmenu":case"left":case"middle":case"up":case"down":case"right":document.createEvent?(event=new Event(c+":"+t),e.target.dispatchEvent(event)):(event=document.createEventObject(),e.target.fireEvent("on"+c+":"+t,event))}}var t=function(e,t,n){try{e.addEventListener(t,n,!1)}catch(c){e.attachEvent("on"+t,n)}};t(window,"mousedown",e),t(window,"mouseup",e),t(window,"click",e),t(window,"contextmenu",e);var n=/Firefox/i.test(navigator.userAgent)?"DOMMouseScroll":"mousewheel";t(window,n,e)}();
$("body").on({
click: function(){alert("left click");},
contextmenu: function(){alert("right click");}
});
Oold old post - but thought would share with complete answer to people asking above about all mouse click event types.
Add this script so it applies to the entire page:
var onMousedown = function (e) {
if (e.which === 1) {/* Left Mouse Click */}
else if (e.which === 2) {/* Middle Mouse Click */}
else if (e.which === 3) {/* Right Mouse Click */}
};
clickArea.addEventListener("mousedown", onMousedown);
Note: Make sure you 'return false;' on the element being clicked - is really important.
Cheers!
$(document).ready(function () {
var resizing = false;
var frame = $("#frame");
var origHeightFrame = frame.height();
var origwidthFrame = frame.width();
var origPosYGrip = $("#frame-grip").offset().top;
var origPosXGrip = $("#frame-grip").offset().left;
var gripHeight = $("#frame-grip").height();
var gripWidth = $("#frame-grip").width();
$("#frame-grip").mouseup(function (e) {
resizing = false;
});
$("#frame-grip").mousedown(function (e) {
resizing = true;
});
document.onmousemove = getMousepoints;
var mousex = 0, mousey = 0, scrollTop = 0, scrollLeft = 0;
function getMousepoints() {
if (resizing) {
var MouseBtnClick = event.which;
if (MouseBtnClick == 1) {
scrollTop = document.documentElement ? document.documentElement.scrollTop : document.body.scrollTop;
scrollLeft = document.documentElement ? document.documentElement.scrollLeft : document.body.scrollLeft;
mousex = event.clientX + scrollLeft;
mousey = event.clientY + scrollTop;
frame.height(mousey);
frame.width(mousex);
}
else {
resizing = false;
}
}
return true;
}
});
With jquery you can use event object type
jQuery(".element").on("click contextmenu", function(e){
if(e.type == "contextmenu") {
alert("Right click");
}
});
$.fn.rightclick = function(func){
$(this).mousedown(function(event){
if(event.button == 2) {
var oncontextmenu = document.oncontextmenu;
document.oncontextmenu = function(){return false;};
setTimeout(function(){document.oncontextmenu = oncontextmenu;},300);
func(event);
return false;
}
});
};
$('.item').rightclick(function(e){
alert("item");
});
you can try this code:
event.button
Return Value: A Number, representing which mouse button that was pressed when the mouse event occured.
Possible values:
0 : Left mouse button
1 : Wheel button or middle button (if present)
2 : Right mouse button
Note: Internet Explorer 8 and earlier has different return values:
1 : Left mouse button
2 : Right mouse button
4 : Wheel button or middle button (if present) Note: For a left-hand configured mouse, the return values are reversed
$.event.special.rightclick = {
bindType: "contextmenu",
delegateType: "contextmenu"
};
$(document).on("rightclick", "div", function() {
console.log("hello");
return false;
});

Categories