Skip to content
Related Articles

Related Articles

Improve Article
JavaScript contextmenu MouseEvent
  • Last Updated : 08 Mar, 2021

When we click the right mouse button on our desktop, a menu-like box appears and this box is called the context menu. In JavaScript, a context menu event runs when a user tries to open a context menu. This can be done by clicking the right mouse button. 

This article demonstrates executing any operation when we click the right mouse button. For example, we want to change the background color of a box when we click the right mouse button.


<!DOCTYPE html>
<html lang="en">
    <meta charset="UTF-8" />
    <meta http-equiv="X-UA-Compatible" 
          content="IE=edge" />
    <meta name="viewport" 
          content="width=device-width, initial-scale=1.0" />
  <!-- Adding some CSS -->
    .context {
      border: 1px solid black;
      background: gREEN;
      width: 200px;
      padding: 10px;
      color: white;
    <div class="context">
      <p>Click right mouse buttom</p>
    <!-- JavaScript code to change content when 
         we click right mouse buttom -->
      // To prevent default operation of right mouse click
      document.addEventListener("contextmenu", (e) => {
      const contextMenu = document.querySelector(".context");
      contextMenu.addEventListener("contextmenu", (e) => {
        contextMenu.textContent = "GeeksForGeeks";

Output : The following output will be shown in the browser and when we click the right mouse button on the box in the above image.

  • Before right click:
  • After right click:

Note: Using this method we can perform a lot of things, we can add a menu on our right-click.

My Personal Notes arrow_drop_up
Recommended Articles
Page :