Friday, 2 February 2018

javascript - 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');
});

Answer



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!');
}
});

No comments:

Post a Comment

casting - Why wasn't Tobey Maguire in The Amazing Spider-Man? - Movies & TV

In the Spider-Man franchise, Tobey Maguire is an outstanding performer as a Spider-Man and also reprised his role in the sequels Spider-Man...