Triggering Onclick Event Using Middle Click

Triggering onclick event using middle click

EDIT

This answer has been deprecated and doesn't work on Chrome. You will most probably end up using the auxclick event, but please refer to other answers below.

/EDIT


beggs' answer is correct, but it sounds like you want to prevent the default action of the middle click. In which case, include the following

$("#foo").on('click', function(e) {
if (e.which == 2) {
e.preventDefault();
alert("middle button");
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<a id="foo" href="http://example.com">middle click me</a>

Emulating middle click on element with an onclick event

To the best of my understanding, as long as that inline click handler is there, it will fire on every click event on that element, but here are two workarounds I've come up with.

  1. If you really can't modify the DOM even for an instant, then the first option won't serve. It cheats by changing the DOM and then restoring it, hopefully before anyone notices.

  2. The second option avoids the need to click the link at all by reading its attributes and using them to open a new tab, without firing a new click event. (This relies on the script having a basic understanding of link element's markup. Specifically, the code I've written here simply assumes that the "link" element has a valid url in its href attribute -- but if necessary, you could make other, more complex assumptions, and act conditionally based on the properties that the "link" element turns out to have at runtime.)

Note: A third alternative would be create a custom event that has all the same core behavior as the built-in click event but without actually being a click event, the idea being to fool the onclick handler into sleeping through the event. I'm not sure how much work it would take to do a sufficiently good job of rebuilding this particular wheel. Maybe it wouldn't be too bad?



In this script, the functions that open the new tab are triggered by button clicks, but of course this is just for demo purposes, and you'd presumably trigger them on page load or as callbacks to some other action. And the anchor element in the snippet has been changed slightly, too, for space-saving reasons

.

(Because the direct call to window.open doesn't appear to work properly in the Stack Overflow snippet, I followed your lead and pasted the code into a fiddle so it can be seen running in all its nominal glory.)

const
// Identifies some DOM elements
cheatButton = document.getElementById("cheat-button"),
mimicButton = document.getElementById("mimic-button"),
exampleLink = document.getElementById("example-link"),

// Defines an event to be dispatched programmatically
middleClick = new MouseEvent("click", {button: 1, which: 2});

// Demonstrates calling the functions
cheatButton.addEventListener("click", emulateMiddleClick); // Option 1
mimicButton.addEventListener("click", followLink); // Option 2

// Defines the functions
function emulateMiddleClick(){
const onclickHandler = exampleLink.onclick; // Remembers onclick handler
exampleLink.onclick = ""; // Supresses onclick handler
exampleLink.dispatchEvent(middleClick); // Dispatches middle click
exampleLink.onclick = onclickHandler; // Restores onclick handler
}

function followLink(){
if(!exampleLink.href){ return; } // In case href attribute is not set
const {href, target} = exampleLink; // Gets props by using "destructuring"

// This doesn't seem to work in the Stack Overflow snippet...
window.open(href, (target || "_blank")); // In case target attribute is not set

// ...But we can at least log our intention to open a new tab
console.log(`opening: "${href}" (in "${target}")`);
}
div{ margin: 1em; }
button{ padding: 0.3em; border-radius: 0.5em; }
span{ margin: 1.3em; }
<div>
<button id="cheat-button">Fake Click, and Suppress Handler</button>
</div>
<div>
<button id="mimic-button">Follow Link without Clicking</button>
</div>
<a id="example-link"
href="https://www.google.com/"
target="_blank"
onclick="window.open('https://www.google.com/', '', 'width=50, height=50');">
<span>Middle Click Me</span>
</a>

Middle button click event

I noticed an issue with mouse button #3 in chrome (didn't test it on other browsers).

So here's a fix for it (add contextmenu to the triggering events):


EDIT
Thanks to Matevž Fabjančičuse's useful comment.

I confirm that since Chrome 55 (I updated to it a minute ago), the mouse middle click now triggers the new auxclick event.

So a click event can only be triggered by mouse button 1.

Notice that auxclick is triggered by mouse button 2 and 3.

Reference here.

$('div.clickable-href').on('click auxclick contextmenu', function(e) {    e.preventDefault();    console.log(e.which);    console.log(e.type);        if(e.type=="contextmenu"){       console.log("Context menu prevented.");       return;    }                               switch(e.which) {        case 1:            //window.location = $(this).attr('href');            console.log("ONE");            break;        case 2:            //window.open($(this).attr('href'));            console.log("TWO");            break;        case 3:            console.log("THREE");            break;    }});
.clickable-href{    width:20em;    background-color:#DDD;    text-align:center;    padding:4em 0;    border-radius:8px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="clickable-href"> CLICK ME - Test all 3 mouse buttons!</div>

Why does middle-click not trigger 'click' in several cases?

The click event is generally fired for the left mouse button, however, depending on the browser, the click event may or may not occur for the right and/or middle button.

In Internet Explorer and Firefox the click event is not fired for the right or middle buttons.

Therefore, we cannot reliably use the click event for event handlers on the middle or right button.

Instead, to distinguish between the mouse buttons we have to use the mousedown and mouseup events as most browsers do fire mousedown and mouseup events for any mouse button.

in Firefox and Chrome event.which should contain a number indicating what mouse button was pressed (1 is left, 2 is middle, 3 is right).

In Internet Explorer on the other hand, event.button indicates what mouse button was clicked (1 is left, 4 is middle, 2 is right);

event.button should also work in Firefox and other browsers, but the numbers can be slightly different (0 is left, 1 is middle, 2 is right).

So to put that together we usually do something like this :

document.onmousedown = function(e) {
var evt = e==null ? event : e;

if (evt.which) { // if e.which, use 2 for middle button
if (evt.which === 2) {
// middle button clicked
}
} else if (evt.button) { // and if e.button, use 4
if (evt.button === 4) {
// middle button clicked
}
}
}

As jQuery normalizes event.which, you should only have to use that in jQuery event handlers, and as such be doing:

$('div a').on('mousedown', function(e) {
if (e.which === 2) {
// middle button clicked
}
});

In other words you can't use the onclick event, so to simulate it you can use both mousedown and mouseup.

You can add a timer to limit the time allowed between the mousedown and mouseup event, or even throw in a mousemove handler to limit the movement between a mousedown and mouseup event, and make the event handler not fire if the mouse pointer moved more than ten pixels etc. the possibilites are almost endless, so that shouldn't really be an issue.

$('#test').on({
mousedown: function(e) {
if (e.which === 2) {
$(this).data('down', true);
}
},
mouseup: function(e) {
if (e.which === 2 && $(this).data('down')) {
alert('middle button clicked');
$(this).data('down', false);
}
}
});

Is it possible to trigger mouse middle click event using Javascript?

Had the same question, did a lot of digging, and this is what I ended up using:

if ( window.CustomEvent ) {
var middleClick = new MouseEvent( "click", { "button": 1, "which": 2 });
jQuery(".selector")[0].dispatchEvent( middleClick );
}

How to detect middle mouse button click?

onclick is not tied to a mouse, but more on the target element itself.

Here's how to detect whether an element is middle clicked:

document.body.onclick = function (e) {
if (e && (e.which == 2 || e.button == 4 )) {
console.log('middleclicked')
}
}

How can I handle the Angular (click) event for the middle mouse button?

For secondary mouse buttons, you can handle the auxclick event. In the following example, the click event is triggered by the primary mouse button, and the auxclick event is triggered by the other mouse buttons.

<a (click)="onClick($event)" (auxclick)="onAuxClick($event)">...</a>
onClick(event: MouseEvent) {
console.log("click - button", event.button, event.which);
}

onAuxClick(event: MouseEvent) {
console.log("auxclick - button", event.button, event.which);
}

See this stackblitz for a demo. Please note that the same method can handle both events. I call different methods in the demo to show which event is handled.

Issue with onClick() and middle button on mouse

You're right. You need a mousedown or mouseup event to determine which mouse button was actually clicked.

But first of all, you need to get rid of that inline-event handler onclick and follow the shining road of unobtrusive javascript.

Thatfor you need to give that anchor a id or class tag to identify it (Of course you may also choose to select that anchor with a css selector). Lets assume we have added a class with the name myClazzz :)

javascript:

$(function(){
$('.myClazzz').bind('mouseup', function(e){
switch(e.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!');
}
});
});

The which property within a mousedown / mouseup event handler will contain a number which indicates which mousebutton was clicked.



Related Topics



Leave a reply



Submit