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.
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.
Share Improve this question edited Feb 1, 2014 at 20:12 BenMorel 36.5k51 gold badges205 silver badges335 bronze badges asked Feb 29, 2012 at 14:19 Keith L.Keith L. 2,12412 gold badges41 silver badges64 bronze badges 2- Don't use intrinsic event handler attributes. Use DOM event binding instead. – Quentin Commented Feb 29, 2012 at 14:37
- I've tried, but it did not work for me. Maybe because the table is loaded later (and does not appear in source code of the rendered page) – Keith L. Commented Feb 29, 2012 at 14:44
2 Answers
Reset to default 15The 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.
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;
}
}