What is a Context Menu?
A context menu is a menu that pops up every time you press right-click on your mouse. It is also referred to as right-click menu but the professional term is Context Menu.
A customized context menu or custom context menu acts the same as a context menu but with additional or new features.
Advantages of a custom context menu
Provides a new user experience
Can act as a quick-access menu
Represents the knowledge of the developer
Source Code
The source code consists of 3 parts :
HTML
CSS
Javascript
HTML
<!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">
<title>Context Menu</title>
<!-- Adding the stylesheet -->
<link rel=stylesheet href="./app.css" />
<!-- Using Font Awesome For Icons -->
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/6.1.1/css/all.min.css"
integrity="sha512-KfkfwYDsLkIlwQp6LFnl8zNdLGxu9YAA1QvwINks4PhcElQSvqcyVLLD9aMhXd13uQjoXtEKNosOWaZqXgel0g=="
crossorigin="anonymous" referrerpolicy="no-referrer" />
</head>
<body>
<div id="context-menu">
<div>
<i class="fa-regular fa-folder"></i>
new Folder
</div>
<div>
<i class="fa-solid fa-arrow-right"></i>
move
</div>
<div>
<i class="fa-solid fa-scissors"></i>
cut
</div>
<div>
<i class="fa-regular fa-copy"></i>
Copy
</div>
<div>
<i class="fa-regular fa-paste"></i>
Paste
</div>
</div>
<!-- Adding Javascript File -->
<script src="./client.js"></script>
</body>
</html>
CSS
body {
font-family: monospace;
}
#context-menu {
position: fixed;
top: 50px;
left: 150px;
background-color: #2c3e50;
width: 200px;
transition: all 0.5s ease-in-out;
display: none;
}
#context-menu.active {
display: block;
}
#context-menu div {
color: white;
padding: 10px;
border-bottom: 1px solid white;
cursor: pointer;
text-transform: uppercase;
transition: all 0.5s ease-in-out;
letter-spacing: 1px;
}
#context-menu div i {
padding: 0 5px;
}
#context-menu div:hover {
background-color: #27ae60;
}
Javascript
/* Getting the context menu */
const context_menu = document.querySelector('#context-menu')
/* Displaying the context menu */
window.addEventListener('contextmenu', (event) => {
context_menu.classList.remove('active')
event.preventDefault() // preventing default drop down
/* Adjusting the position of the menu */
context_menu.style.top = event.offsetY + 'px'
context_menu.style.left = event.offsetX + 'px'
context_menu.classList.add('active')
})
/* Hiding the context menu when clicked outside the menu */
window.addEventListener('click', (event) => {
context_menu.classList.remove('active')
})
References
For more information about the context menu and its event , please go through the documentation.