Popular Posts

Create Custom Right Click / Context Menu using HTML, CSS & JavaScript

Web apps are using their own customized context menu to present users with relevant actions. In a web browser, when a right-click action is performed, contextmenu event gets fired. In order to deploy a customized context menu, we’ll need to prevent default behaviour, and then set up, trigger, and position our own menu.


HTML
<div id="context-menu">
  <div class="item">
    <i class="fa fa-cut"></i> Cut
  </div>
  <div class="item">
    <i class="fa fa-clone"></i> Copy
  </div>
  <div class="item">
    <i class="fa fa-paste"></i> Paste
  </div>
  <div class="item">
    <i class="fa fa-trash-o"></i> Delete
  </div>
  <hr>
  <div class="item">
    <i class="fa fa-refresh"></i> Reload
  </div>
  <div class="item">
    <i class="fa fa-times"></i> Exit
  </div>
</div>
CSS
body {
  margin:0px;
  font-family:"Open Sans",sans-serif;
}
#context-menu {
  position:fixed;
  z-index:10000;
  width:150px;
  background:#1b1a1a;
  border-radius:5px;
  transform:scale(0);
  transform-origin:top left;
}
#context-menu.active {
  transform:scale(1);
  transition:transform 300ms ease-in-out;
}
#context-menu .item {
  padding:8px 10px;
  font-size:15px;
  color:#eee;
}
#context-menu .item:hover {
  background:#555;
}
#context-menu .item i {
  display:inline-block;
  margin-right:5px;
}
#context-menu hr {
  margin:2px 0px;
  border-color:#555;
}
JS
window.addEventListener("contextmenu",function(event){
  event.preventDefault();
  var contextElement = document.getElementById("context-menu");
  contextElement.style.top = event.offsetY + "px";
  contextElement.style.left = event.offsetX + "px";
  contextElement.classList.add("active");
});
window.addEventListener("click",function(){
  document.getElementById("context-menu").classList.remove("active");
});