< BACK TO COMPONENTS

Create a Custom Right Click Context Menu using HTML, CSS, JavaScript

Faraz

By Faraz -

Learn to implement a custom right click context menu in HTML, CSS, and JavaScript to offer users quick access to actions. Improve your web app's user experience now!


Create a Custom Right Click Context Menu using HTML, CSS, JavaScript.jpg

In the dynamic world of web development, user experience plays a pivotal role in the success of any application. As developers, we continually strive to create websites that not only look visually appealing but also offer seamless and intuitive interactions for users. One essential aspect of user interface design that significantly contributes to this goal is the implementation of context menus.


What are Context Menus?


A context menu, also known as a context-sensitive menu or right-click menu, is a pop-up menu that appears when users interact with an element on a web page, typically through a right-click or a long-press on touch devices. These menus provide users with a list of relevant actions or options based on the context of their interaction. Context menus are versatile tools that allow users to access frequently used commands or perform specific actions without cluttering the main interface.


The Importance of Custom Context Menus


While most web browsers and operating systems come with default context menus, incorporating custom context menus can significantly enhance the user experience. By tailoring context menus to suit the specific needs of your web application, you can empower users with more streamlined and contextually relevant options. Custom context menus provide a sense of familiarity and consistency within your web application, leading to increased user satisfaction and productivity.


Benefits of Context Menus in Web Development


  • Efficiency and Productivity: Context menus enable users to access commonly used functions quickly, saving them the trouble of navigating through multiple pages or menus.
  • Simplified User Interface: By hiding less frequently used options behind context menus, you can declutter the main interface and present users with a cleaner and more focused design.
  • Intuitive Interaction: Context menus appear at the exact location where the user makes their interaction, creating a seamless and contextually-driven user experience.
  • Consistency and Branding: Custom context menus allow you to maintain visual consistency with the rest of your application, promoting brand identity and reinforcing the overall design aesthetics.
  • Versatility: Context menus can be employed in various scenarios, such as managing files, editing content, handling user interactions, and much more, making them an invaluable asset in web development.

Exploring Context Menus in HTML, CSS, and JavaScript


In this comprehensive blog post, we will delve into the world of context menus and learn how to create a custom context menu using the trifecta of web technologies: HTML, CSS, and JavaScript. Whether you are a seasoned developer or a newcomer to the field, this step-by-step guide will walk you through the process of building a functional and visually appealing context menu that will elevate the user experience of your web application.


Let's get started with the first step: setting up the HTML structure for our custom context menu!

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file. In this file, we will include the main structure for our context menu.


After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.


Let's break down the code step by step:


<!DOCTYPE html>: This is the document type declaration, which tells the browser that this is an HTML5 document.


<html lang="en">: This is the opening tag for the root element of the HTML document. The lang attribute is set to "en" (English), indicating the language used in the document.


<head>: The head element contains meta-information about the document, such as the title, character encoding, and CSS stylesheet link.


<title>Context Menu using HTML, CSS and JavaScript</title>: This sets the title of the webpage, which appears in the browser's title bar or tab.


<meta charset="UTF-8" />: This meta tag specifies the character encoding of the document, which is set to UTF-8, a widely used character encoding that supports various languages.


<meta name="viewport" content="width=device-width" />: This meta tag defines the viewport settings for responsive web design, ensuring that the width of the page adapts to the device's width.


<link rel="stylesheet" href="styles.css" />: This is a link to an external CSS stylesheet named "styles.css", which will be used to style the HTML elements in the document.


<body>: The body element contains the visible content of the webpage, such as text, images, and other HTML elements.


<div class="container" oncontextmenu="return showContextMenu(event)">: This div element serves as a container and has an oncontextmenu attribute. The oncontextmenu attribute is an event handler that triggers a JavaScript function called showContextMenu() when the user right-clicks within the container.


<h2>Right Click Here!</h2>: This heading level 2 (h2) element displays the text "Right Click Here!" inside the container.


<div id="pulse"></div>: This empty div element with the id "pulse" is likely used as a visual effect for the context menu. It may be manipulated through CSS or JavaScript to create a pulse animation.


<div id="contextMenu">: This div element with the id "contextMenu" represents the custom context menu that will be displayed when the user right-clicks inside the container.


<ul>: This unordered list element (ul) contains a list of context menu options.


Context Menu Options: Each list item (li) represents a context menu option with an icon and a label.


Options for "Open," "Open in new tab," "Cut," "Copy," "Paste," "Reload," and "Print" have font-awesome icons (represented by the i elements) and descriptive labels (represented by the div elements with the class "name").


There are "break" div elements (with the class "break") inserted to add visual separation between different groups of options in the context menu.


The "Share" option contains a "Share" label and a group of social media icons (font-awesome icons) wrapped in a div with the class "icons."


<script src="script.js"></script>: This script tag includes an external JavaScript file named "script.js," which likely contains the showContextMenu() function and possibly other scripts related to the context menu functionality.


This is the basic structure of our context menu using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the context menu is in place, the next step is to add styling to the context menu using CSS.


Next, we will create our CSS file. In this file, we will use some basic CSS rules to style our context menu.


Here's an explanation of the CSS code block:


The code begins with two @import statements that include external resources. The first one imports the Font Awesome icon library version 4.7.0 from the specified URL. The second one imports the "Roboto Condensed" font from Google Fonts.


The universal selector (*) is used to apply the following styles to all elements in the HTML document:


  • margin: 0px; and padding: 0px;: Removes default margins and paddings for all elements.
  • box-sizing: border-box;: Ensures that the element's width and height include padding and border, not just the content.
  • font-family: 'Roboto Condensed', sans-serif;: Sets the font family for all elements to "Roboto Condensed" with a fallback to a generic sans-serif font family.

The .container class is defined with the following styles:


  • display: flex;: Makes the container a flex container, enabling flexbox layout properties.
  • justify-content: center;: Centers the content horizontally within the container.
  • align-items: center;: Centers the content vertically within the container.
  • width: 100vw; and height: 100vh;: Sets the container's width and height to 100% of the viewport width and height, respectively.
  • font-size: 200%;: Sets the font size of the content inside the container to 200% of the default size.

The ul li selector targets list items (li) within unordered lists (ul) and removes their default list-style.


The #contextMenu ID selector styles a contextual menu as follows:


  • position: absolute;: Positions the menu relative to its closest positioned ancestor.
  • transform-origin: top left; and transform: scale(0);: Sets the origin point and scales the menu to 0, making it invisible.
  • width: 220px;: Sets the width of the menu to 220 pixels.
  • border: 1px solid rgba(100, 100, 100, 0.55);: Adds a border with a slightly transparent gray color.
  • padding: 5px;: Adds padding inside the menu.
  • background: rgba(250, 250, 250, 0.98);: Sets the background color with a slightly transparent white color.
  • box-shadow: 2px 2px 12px 4px rgba(100, 100, 100, 0.4);: Adds a shadow effect.
  • transition: transform 400ms ease-in-out 50ms;: Defines a smooth transition effect when the menu scales in and out.

The #contextMenu.visible selector styles the visible state of the contextual menu (#contextMenu) when it is displayed. When the .visible class is added to the menu, it triggers the following styles:


  • transform: scale(1);: Scales the menu to its original size, making it visible.

The #contextMenu ul li selector styles the list items inside the contextual menu:


  • padding: 5px 3px;: Adds padding around the list items.
  • display: flex; and align-items: center;: Makes the list items flex containers and aligns their content vertically centered.
  • cursor: pointer;: Changes the cursor to a pointer when hovering over the list items.
  • color: rgba(50, 50, 50, 0.9); and font-size: 15px;: Sets the text color and font size for the list items.

The #contextMenu ul li:hover selector styles the list items when they are being hovered over:


  • background: rgba(100, 100, 100, 0.12);: Sets a slightly transparent gray background color when hovering over a list item.

The #contextMenu ul li.disabled selector styles the list items with the disabled class. It makes the text color slightly transparent to indicate that they are disabled.


The #contextMenu ul li.share selector styles a specific type of list item with the class .share:


  • width: 100%;: Sets the width of the list item to 100% of its container.
  • flex-direction: column;, align-items: left;, and flex-wrap: wrap;: Changes the flex direction to a column layout and wraps the content if needed.

The #contextMenu ul li.share > .name selector styles a child element with the class .name that is a descendant of the .share list item. It sets the margin values to adjust the spacing.


The #contextMenu ul li.share .icons selector styles the element with class .icons that is a descendant of the .share list item. It sets the element as a flex container and evenly distributes its child elements with space around them.


The #contextMenu ul li.share .icons > i:hover selector styles the icon elements within the .icons container when they are being hovered over. It changes the background color to a light gray when the icons are hovered.


The #contextMenu ul li i selector styles all icon elements within list items. It sets a fixed width for the icons.


The #contextMenu ul li div.name selector styles a div element with the class .name that is a descendant of list items.


The #contextMenu div.break selector styles div elements with the class .break that are used to create horizontal lines to separate menu items.


The #pulse ID selector styles an element with the ID pulse:


  • position: fixed;: Positions the element relative to the viewport.
  • width: 35px; and height: 35px;: Sets the width and height of the element to 35 pixels.
  • background: rgba(0, 0, 0, 1);: Sets a solid black background color.
  • opacity: 0;: Makes the element invisible.
  • border-radius: 50%;: Gives the element a circular shape.
  • z-index: 100;: Sets the stacking order, making it appear above other elements.

The #pulse.active selector styles the element with the ID pulse when it has the class .active. This class is likely added dynamically using JavaScript to trigger a pulse animation effect.


The @keyframes pulse rule defines a keyframe animation named "pulse":


  • At 0%, the element is fully opaque and scaled down to size 0.
  • At 100%, the element becomes fully transparent and is scaled up to 1.1 times its original size.

This will give our context menu an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

@import url("https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css");
@import url('https://fonts.googleapis.com/css?family=Roboto+Condensed');
* {
  margin:0px;
  padding:0px;
  box-sizing:border-box;
  font-family: 'Roboto Condensed', sans-serif;
}
.container {
  display:flex;
  justify-content:center;
  align-items:center;
  width:100vw;
  height:100vh;
  font-size:200%;
}
ul li {
  list-style:none;
}
#contextMenu {
  position:absolute;
  transform-origin:top left;
  transform:scale(0);
  width:220px;
  border:1px solid rgba(100,100,100,0.55);
  padding:5px;
  background:rgba(250,250,250,0.98);
  box-shadow:2px 2px 12px 4px rgba(100,100,100,0.4);
  transition:transform 400ms ease-in-out 50ms;
}
#contextMenu.visible {
  transform:scale(1);
}
#contextMenu ul li {
  padding:5px 3px;
  display:flex;
  align-items:center;
  cursor:pointer;
  color:rgba(50,50,50,0.9);
  font-size:15px;
}
#contextMenu ul li:hover {
  background:rgba(100,100,100,0.12);
}
#contextMenu ul li.disabled {
  color:rgba(100,100,100,0.5);
  cursor:pointer;
}
#contextMenu ul li.share {
/*   height:40px; */
  width:100%;
  flex-direction:column;
  align-items:left;
  flex-wrap:wrap;
}
#contextMenu ul li.share > .name {
  margin-top:-2px;
  margin-bottom:10px;
  display:block;
}

#contextMenu ul li.share .icons {
  width:100%;
  display:flex;
  justify-content:space-around;
}
#contextMenu ul li.share .icons > i:hover{
  background:#e7e7e7;
}

#contextMenu ul li i {
  width:20px; 
}
#contextMenu ul li div.name {
  padding-left:8px;
}
#contextMenu div.break {
  margin:4px 0px;
  border-top:1px solid rgba(100,100,100,0.5);
}

#pulse {
  position:fixed;
  width:35px;
  height:35px;
  background:rgba(0,0,0,1);
  opacity:0;
  border-radius:50%;
  z-index:100;
}
#pulse.active {
  animation:pulse 400ms ease;
}

@keyframes pulse {
  0% {
    opacity:1;
    transform:scale(0);
  }
  100% {
    opacity:0;
    transform:scale(1.1);
  }
} 

Step 3 (JavaScript Code):

Finally, we need to create a function in JavaScript.


Let's break it down step by step:


window.addEventListener('click', function(e) {...}):

This line adds a click event listener to the window object. Whenever a click event occurs anywhere on the web page, the provided function will be executed.


function showContextMenu(e) {...}:

This is the function responsible for showing the context menu. It takes an event e as an argument, which represents the click event triggered by the user.


Inside the showContextMenu function:


a. var pulse = document.getElementById('pulse');:

This line fetches an element with the id attribute "pulse" from the HTML document and stores it in the variable pulse. It seems like this element is used to create a visual effect, possibly representing a pulsating animation.


b. var menu = document.getElementById('contextMenu');:

This line retrieves an element with the id attribute "contextMenu" from the HTML document and stores it in the variable menu. This element is likely the context menu that should be displayed when the function is called.


c. The following block of code determines the position of the context menu and the pulse effect based on the user's click location (e.clientX and e.clientY represent the horizontal and vertical coordinates of the mouse pointer at the time of the click):

  • If the click is near the right edge of the window (e.clientX > window.innerWidth - 220), the context menu will be positioned to the left of the click (menu.style.left = (e.clientX - 220) + 'px';) and its transformation origin will be set to the top right (menu.style.transformOrigin = 'top right';). This likely means the context menu will open towards the left.
  • Otherwise, if the click is not near the right edge, the context menu will be positioned exactly where the click occurred (menu.style.left = e.clientX + 'px';).
  • Additionally, the pulse element is also positioned based on the click coordinates.

d. pulse.classList.add('active');:

This adds the CSS class 'active' to the pulse element. This class is likely responsible for triggering the pulsating animation.


e. A setTimeout function is used to remove the 'active' class from the pulse element after 300 milliseconds, creating a brief pulsating effect.


f. document.getElementById('contextMenu'):

This line seems to be unnecessary and doesn't serve any purpose. It's likely a mistake and can be removed.


g. menu.classList.add('visible');:

This line adds the CSS class 'visible' to the menu element, making it visible. The 'visible' class probably contains CSS styles to display the context menu.


h. menu.style.transformOrigin = 'top left';:

This line sets the transformation origin of the menu element to the top left. This might affect the way the context menu is displayed or animated.


i. return false;:

The function returns false, which is often used to prevent the default behavior of an event. In this case, it's likely used to prevent the default context menu (if any) from showing up when right-clicking on the page.


Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

window.addEventListener('click',function(e){
  var menu = document.getElementById('contextMenu');
  menu.classList.remove('visible');
});
function showContextMenu(e) {
   var pulse = document.getElementById('pulse');
  var menu = document.getElementById('contextMenu');
  if(e.clientX > window.innerWidth- 220) {
    menu.style.left = (e.clientX-220)+'px';
    menu.style.transformOrigin = 'top right';
  } else {
    menu.style.left = e.clientX+'px';      
  }
  pulse.style.left = e.clientX-10+'px';
  menu.style.top = e.clientY+'px';  
  pulse.style.top = (e.clientY-10)+'px';  
  pulse.classList.add('active');
  setTimeout(function(){
    document.getElementById('pulse').classList.remove('active');
  },300);
    document.getElementById('contextMenu')
  menu.classList.add('visible');
  menu.style.transformOrigin = 'top left';
  return false;
}

Final Output:

Create a Custom Right Click Context Menu using HTML, CSS, JavaScript.gif

Conclusion:

In conclusion, context menus are indispensable tools for improving user interaction and productivity in web development. Throughout this blog post, we explored the concept of context menus and learned how to create a custom context menu using HTML, CSS, and JavaScript.


By implementing custom context menus, you can offer users a more streamlined and contextually relevant experience, enabling them to access frequently used actions and options effortlessly. The benefits of custom context menus include enhanced efficiency, a simplified user interface, intuitive interactions, consistent branding, and remarkable versatility.


As web developers, our goal is to create user-friendly applications that not only look appealing but also function seamlessly. By incorporating custom context menus, you can significantly elevate the user experience of your web application and leave a lasting impression on your audience.


So, why wait? Implement the step-by-step guide we've provided, and unlock the potential of custom context menus to revolutionize your web application's usability. Embrace this powerful feature, and watch as your users engage with your application more efficiently and with greater satisfaction.


Take the next step in improving your web application's user experience by creating a custom context menu today. Happy coding!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee.

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post