12

I want to trigger mouse middle click event using javascript. Is it possible to trigger mouse middle click using Javascript?

I want it because it is pasting last selected object from clipboard.

Thanks, Jimit

Jimit
  • 2,201
  • 7
  • 32
  • 66

2 Answers2

12

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 );
}
Mike Willis
  • 1,493
  • 15
  • 30
  • 1
    Thanks this helps a lot! See also http://stackoverflow.com/questions/41065688/trigger-native-browser-behavior-for-middle-click-on-a-link?noredirect=1#comment69338498_41065688 – donquixote Dec 09 '16 at 17:53
  • For me this even worked on a link that is not part of the DOM.. but this could be browser-dependent. – donquixote Dec 09 '16 at 17:54
  • 2
    If I do this on an anchor tag, shouldn't the window stay focused and not focus on the newly opened tab/window?@donquixote – tjvg1991 Jun 20 '18 at 06:52
  • For a middle-click, I think "which" should be 2, not 1. – Doin Mar 01 '20 at 19:02
  • @Doin looks like 1 is correct for middle button according to this: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/button – Mike Willis Mar 02 '20 at 20:12
  • 1
    That's correct for "button". "which" uses a different numbering scheme: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which – Doin Mar 03 '20 at 03:15
  • @Doin oh yea you're right. That's weird, ok I'll update the answer, thanks! – Mike Willis Mar 03 '20 at 15:25
-2

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.