JSFiddle - React, Tailwind, and code Playground
HTML
<div id="target"></div>
CSS
#target {
border: #c0c0c0 solid 1px;
background-color: #f2f2f2;
width: 100px;
height: 100px;
}
.menu {
position: absolute;
display: none;
border: #c0c0c0 solid 1px;
font-family: calibri, arial, helvetica, sans serif;
}
div .menuOption {
padding: 4px 8px;
background-color: #f0f0f0;
}
div .active:hover {
cursor: pointer;
background-color: #99cb33;
color: #ffffff;
}
div .inactive {
color: #c0c0c0;
}
JavaScript
$("#target").bind("contextmenu",function(e){
var newMenu = buildMenu(boxMenu,this);
var winWidth = $(window).width();
var winHeight = $(window).height();
// Menu not off screen to right
if ((e.pageX + newMenu.outerWidth()) > winWidth)
newMenu.css("left", winWidth - newMenu.outerWidth());
else
newMenu.css("left", e.pageX);
// Menu not off screen at bottom
if ((e.pageY + newMenu.outerHeight()) > winHeight)
newMenu.css("top", winHeight - newMenu.outerHeight());
else
newMenu.css("top", e.pageY);
newMenu.show();
return false;
});
// Clears all menus when click the document (as an example)
// Make your own custom trigger for when you want to dismiss them.
$(document).bind("mouseup", function(e) {
if (e.which == 1) { $(".menu").hide(); }
});
// Takes a menu variable and the target element, builds the HTML and returns a reference to the menu.
function buildMenu(menu, target) {
if ($("#" + menu.name).length) {
var m = $("#" + menu.name);
m.hide();
return m;
}
// Build overall menu
var m = document.createElement("div");
m.className = "menu";
m.target = target;
m.id = menu.name;
// Build options for menu based on menu variable
for (var i = 0; i < menu.items.length; i++) {
var item = document.createElement("div");
if (menu.items[i].active)
item.className = "menuOption active";
else
item.className = "menuOption inactive";
item.innerHTML = menu.items[i].text;
item.onclick = menu.items[i].command;
m.appendChild(item);
}
$("body").append(m);
return $(m);
}
// Menus
var boxMenu = {
name: "boxmenu",
target: null,
items: [{
text: "Option 1",
command: function() {
// This is the menu option clicked
if ($(this).hasClass("active")) {
...