Open In App

How to display message when the contextmenu event is triggered using jQuery ?

Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we will learn how to display a message when a contextmenu event is triggered using jQuery. A context menu in a browser is a menu with multiple choices that appears when the user right-clicks.

Approach: We will be using the contextmenu event to check if the user has triggered the context menu on the page. This can be done in two ways. The first one is using the contextmenu() method that listens for the contextmenu event on the element it is used on. The second is using the on() method to listen for the contextmenu event. The event handler function can then be used to display a message to the user.

Syntax:

$("element_selected").contextmenu(function () {
   alert("Message to be displayed");
});

OR

$("element_selected").on('contextmenu', function () {
  alert("Message to be displayed");
});

Example: This example shows both the ways by which one can display a message when the contextmenu event is triggered.

HTML




<head>
    <!-- Getting the jQuery library -->
    </script>
    <style>
        .elem1, .elem2 {
        height: 50px;
        border: 1px solid;
        margin: 10px;
        }
    </style>
</head>
<body>
    <h1 style="color: green;">
        GeeksforGeeks
    </h1>
      
    <div class="elem1">
      
        <p>This is element 1</p>
      
    </div>
      
    <div class="elem2">
      
        <p>This is element 2</p>
      
    </div>
    <script>
        // Using the contextmenu() method
        // to display the message
        $(".elem1").contextmenu(function () {
          
        // Display the message
        alert("Element 1 message");
        });
          
        // Using the on() method to check
        // for the contextmenu event
        $(".elem2").on('contextmenu', function () {
          
        // Display the message
        alert("Element 2 message");
        });
    </script>
</body>


Output: Write click on any div.



Last Updated : 15 Feb, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads