Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JS: detect right click without jQuery (inline)

I'm calling a function, that builds a table which includes several links.

I want to check if a link has been clicked with right or left mouse.

I tried to add the following part to the <a> hyperlink.

onmousedown="function mouseDown(e){
switch (e.which) {
   case 1: alert('left'); break;
   case 2: alert('middle'); break;
   case 3: alert('right'); break; }
}"

But nothing happens If I click on a link.

like image 200
Keith L. Avatar asked Feb 29 '12 14:02

Keith L.


2 Answers

The html:

<a href="#" onmousedown="mouseDown(event);">aaa</a>​​​​​​​​​​​​​​​​​​​​​​​​​​​

The javascript:

function mouseDown(e) {
  e = e || window.event;
  switch (e.which) {
    case 1: alert('left'); break;
    case 2: alert('middle'); break;
    case 3: alert('right'); break; 
  }
}​

The demo.

like image 112
xdazz Avatar answered Sep 30 '22 17:09

xdazz


Here's a modification of xdazz's answer that supports browsers that use e.button, normalizes the value, and stores it in e.which. The added lines are what are used in the JQuery library.

function mouseDown(e) {
  e = e || window.event;
  if ( !e.which && e.button !== undefined ) {
    e.which = ( e.button & 1 ? 1 : ( e.button & 2 ? 3 : ( e.button & 4 ? 2 : 0 ) ) );
  }
  switch (e.which) {
    case 1: alert('left'); break;
    case 2: alert('middle'); break;
    case 3: alert('right'); break; 
  }
}​
like image 35
Sean N. Avatar answered Sep 30 '22 18:09

Sean N.