Mike Mike - 1 year ago 44
jQuery Question

How can I prevent a user from middle clicking a link with javascript or jquery

I want to prevent the user from being able to middle click a certain link to open a new tab. I have tried the following:

$(window).on('mouseup', '.sptDetails', function(e){
if(e.button == 1){
return false;

This doesn't seem to work.


It's an unfortunate combination of jQuery and the browser. To prevent the new tab from opening you have to use the click event (rather than mouseup), but jQuery does not run delegate click handlers for mouse buttons other than the left one:

// Avoid non-left-click bubbling in Firefox (#3861)
if ( delegateCount && !(event.button && event.type === "click") ) {

What you can do is using a non-delegate handler and check the target element yourself: http://jsbin.com/ojoqap/10/edit. This works on Chrome, at least (inspired by @Abraham).

$(document).on("click", function(e) {
  if($(e.target).is("a[href]") && e.button === 1) {