Skip to content

Instantly share code, notes, and snippets.

@janderudder
Last active September 2, 2022 16:15
Show Gist options
  • Save janderudder/ebe431db41d819d19562ed0eb87d7458 to your computer and use it in GitHub Desktop.
Save janderudder/ebe431db41d819d19562ed0eb87d7458 to your computer and use it in GitHub Desktop.
context menu - custom web context menu example
<!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 (custom)</title>
</head>
<body>
<p>Right-click to display the context menu.</p>
<div class="context-menu" style="display:none">
<ul>
<li><div>item 1</div></li>
<li><div>item 2</div></li>
<li><div>item 3</div></li>
</ul>
</div>
<style>
.context-menu {
position: absolute;
width: 200px;
height: fit-content;
background-color: white;
border: 1px solid lightgray;
box-shadow: 1px 1px 6px lightgray;
}
.context-menu ul {
list-style: none;
width: 100%;
margin: 2px 0;
padding-inline: 3px;
line-height: 1.4em;
}
.context-menu li {
margin-inline: auto;
padding: 2px 0;
border-bottom: 1px ridge lightgray;
}
.context-menu li div {
padding: 2px 10px;
}
.context-menu li:last-of-type {
border-bottom: none;
}
.context-menu li div:hover {
background-color: rgb(243, 242, 242);
cursor: pointer;
}
</style>
<script>
const contextMenu = document.querySelector('.context-menu')
function openContextMenuAt(x, y) {
contextMenu.style.left = `${x}px`
contextMenu.style.top = `${y}px`
contextMenu.style.display = 'block'
}
function closeContextMenu() {
contextMenu.style.display = 'none'
}
// open menu
window.addEventListener('contextmenu', event => {
event.preventDefault()
openContextMenuAt(event.clientX, event.clientY)
})
// close menu on click anywhere
contextMenu.addEventListener('click', event => {
event.stopPropagation()
})
// prevent closing when clicking inside menu
window.addEventListener('click', () => {
closeContextMenu()
})
// sample actions in the menu
const menuItems = document.querySelectorAll('.context-menu li')
const bgColor = ['darkseagreen', 'darkred', 'darkblue']
for (let i=0; i<menuItems.length; ++i) {
menuItems[i].addEventListener('click', () => {
document.body.style.backgroundColor = bgColor[i]
document.querySelector('p').style.color = 'white'
})
}
</script>
<style>
* {box-sizing: inherit;}
body {box-sizing: border-box; font-size: 16pt; font-family: sans-serif; transition: background-color 500ms ease;}
p {transition: color 500ms ease;}
</style>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment