×

jQuery Tutorial

jQuery Examples

jQuery Practice

How to distinguish between left and right mouse click with jQuery?

Learn, how to distinguish between left and right mouse click with jQuery?
Submitted by Pratishtha Saxena, on November 16, 2022

When a mouse click is performed on an element, we can get to know whether the mouse was left-clicked or right-clicked. When we want to know just whether the mouse was clicked or not, we can check it using jQuery' mousedown() method.

The mousedown() method only detects the down clicks. It does not return anything for the moment when the click is released. For that, we use mouseup() method in jQuery which detects mousing click releasing from the element.

Syntax:

$('selector').mousedown();
$('selector').mousedown(function);

It takes one optional parameter – function. The function is the custom function that can be defined to do some tasks when the mousedown() method gets triggered.

But when we want to specifically get whether it was a left click or right click, along with mousedown() method we need to apply some switch cases attached to the which property of the event.

When the mouse is clicked, the which property provides us with three options – left click, center click & right click. These cases are paired with switch to get the results.

  • Case 1: Left Click
  • Case 2: Centre Click
  • Case 3: Right Click

jQuery example to distinguish between left and right mouse click

<!DOCTYPE html>
<html lang="en">
  <head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
    <title>Document</title>
    <style>
      div{
      height: 200px;
      width: 200px;
      background-color: cadetblue;
      border: 2px solid;
      }
    </style>
  </head>
  
  <body>
    <h2>Distinguish Between Left & Right Mouse Click Using jQuery.</h2>
    <p>Click within the following box and get to know whether it was a left or right mouse click.</p>
    <hr>
    <div></div>
    <hr>
    <h3></h3>
  </body>
  
  <script type="text/javascript">
    $(document).ready(function(){
        $('div').mousedown(function(event){
            switch(event.which){
                case 1:
                    $('h3').html('Left Click');
                    break;
                case 2:
                    $('h3').html('Center Click');
                    break;
                case 3:
                    $('h3').html('Right Click');
                    break;
                default:
                    break;
            }
        });
    });
  </script>
</html>

Output:

Example: Distinguish between left and right mouse click




Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.