Organizational Research By

Surprising Reserch Topic

triggering onclick event using middle click


triggering onclick event using middle click  using -'javascript,jquery'

I am using the onclick event of a hashed link to open a <div> as a pop up. But the middle click does not trigger the onclick event but only takes the href attribute value of the link and loads the URL in a new page. How can I use middle click to open the <div> as a popup?
    

asked Sep 9, 2015 by AltNewport
0 votes
43 views



Related Hot Questions

4 Answers

0 votes

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").live('click', function(e) { 
   if( e.which == 2 ) {
      e.preventDefault();
      alert("middle button"); 
   }
});

preventDefault() will stop the default action of the event.

answered Sep 9, 2015 by CarmineStrat
0 votes

You can use

event.button

to identify which mouse button was clicked.

Returns an integer value indicating the button that changed state.

  • 0 for standard 'click', usually left button
  • 1 for middle button, usually wheel-click
  • 2 for right button, usually right-click

Note that this convention is not followed in Internet Explorer: see QuirksMode for details.

The order of buttons may be different depending on how the pointing device has been configured.

Also read

Which mouse button has been clicked?

There are two properties for finding out which mouse button has been clicked: which and button. Please note that these properties don’t always work on a click event. To safely detect a mouse button you have to use the mousedown or mouseup events.

answered Sep 9, 2015 by NoelQTOjupbv
0 votes

The proper method is to use .on, as .live has been deprecated and then removed from jQuery:

$("#foo").on('click', function(e) { 
   if( e.which == 2 ) {
      e.preventDefault();
      alert("middle button"); 
   }
});

Or if you want the "live" like feel and #foo is not on your page on document start:

$(document).on('click', '#foo', function(e) { 
   if( e.which == 2 ) {
      e.preventDefault();
      alert("middle button"); 
   }
});

original answer

answered Sep 9, 2015 by MaurineFourn
0 votes

jQuery provides a .which attribute on the event that gives the click button id from left to right as 1, 2, 3. In this case you want 2.

Usage:

$("#foo").live('click', function(e) { 
   if( e.which == 2 ) {
      alert("middle button"); 
   }
});

Adamantium's answer will also work but you need to watch out for IE as he notes:

$("#foo").live('click', function(e) { 
   if((!$.browser.msie && e.button == 1) || ($.browser.msie && e.button == 2)) { 
     alert("middle button"); 
   } 
});

Also remember the .button attribute is 0-indexed not 1-indexed like .which.

answered Sep 9, 2015 by WillisLukis0

...