Cannot use jquery click event handler to detect right click

When trying to detect a right mouse click using jquery, I noticed that the click event handler does not fire with the right mouse click, while the mousedown or mouseup event handler does.

For example, after right-clicking on a test div, perform the following "!!" checks:

$('#test').mousedown(function(e) { alert('testing'); }); 

However, the following does not :

 $('#test').click(function(e) { alert('testing!'); }); 

Does anyone know why?

+6
source share
4 answers

As the article says:

There are no click events for right-clicking in any browser.

This way you are left with mousedown and mouseup in most browsers.

+8
source

When you are in mousedown, even the fired has an event.which

Taken from here: How to distinguish left and right mouse button from jQuery

 $('#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'); } }); 

So instead of using .click (), use mousedown and check for cases.

+12
source

Not sure which browsers you tested, but according to MSDN onclick fires "when the user presses the left button . Ie, by definition, this does not happen for right (or middle) clicks. Given that on MSDN you can expect IE to behave this way no matter what other browsers do.

(Onclick also works for some things other than the mouse, for example, to change certain form elements using the keyboard, etc.)

I know jQuery is trying to normalize the behavior of browsers, but if the browser does not fire the event at all ...

There is at least one jQuery plugin that I know of that implements right-click: http://abeautifulsite.net/blog/2008/05/jquery-right-click-plugin/ (I have not used it, but it looks good, except that it notes that Opera does not support it).

0
source

I also tried the following code to catch the right mouse click for a specific class of elements.

 $(".brick").mousedown(function (event) { if (event.which === 3) { currentRightClickedTileID = $(this).attr("id"); } }); 

This code does not always right-click.

0
source

Source: https://habr.com/ru/post/896842/


All Articles