blog-banner

Responding To Various Mouse Clicks With jQuery

  • Jquery

Mouse Clicks with jQuery

The mouse has been the primary medium of input for decades. Normally there are three types of mouse clicks. They are left, right and middle click.

In jQuery, we all knew there is a click() method that acts as an event handler to capture this action.

$(selector).click();

But how to capture a specific click. For example, if we want to make some changes only on the left click or only on the right click.

Of course, the common click() handler will not help us in this case. So we need to move to target specific click events.

But how to capture this specific click action. Is it possible? Yes, it is with the below code snippet,

$(selector).mousedown(function(e){
  if (e.which == 1) {
    // this is left click event.
  }
  if (e.which == 2) {
    // this is middle click event.
  }
  if (e.which == 3) {
    // this is right click event.
  }
});

With mousedown() method we can capture the specific clicks.

This works on the majority of browsers like Chrome, Firefox, IE, and Safari. By capturing the code value returned by e.which we can determine the specific click. Hope this blog may help you.