Create A Simple Touch-enabled Context Menu using jQuery

Create A Simple Touch-enabled Context Menu using jQuery
File Size: 1.85 KB
Views Total: 5048
Last Update:
Publish Date:
Official Website: Go to website
License: MIT
   

A mimalistic jQuery script that creates a fully customisable context menu to replace the default right-click menu on your web page. Press right-click to show the context menu. For phone long press on the page.

How to use it:

1. Create the Html for a context menu.

<div class="context" hidden>

  <div class="context_item">
    <div class="inner_item"> Item 1 </div>
  </div>

  <div class="context_item">
    <div class="inner_item"> Item 2 </div>
  </div>

  <div class="context_item">
    <div class="inner_item"> Item 3 </div>
  </div>

  <div class="context_hr"></div>

  <div class="context_item">
    <div class="inner_item"> Item 4 </div>
  </div>

  <div class="context_item">
    <div class="inner_item"> Item 5 </div>
  </div>

</div>

2. Style the context menu in the CSS.

.context {
  font-size: 1.1em;
  position: absolute;
  width: 200px;
  height: auto;
  padding: 5px 0px;
  border-radius: 5px;
  top: 10;
  left: 10;
  background-color: #27ae60;
  box-shadow: 0 12px 15px 0 rgba(0, 0, 0, 0.24);
  color: #fff;
}

.context .context_item {
  height: 32px;
  line-height: 32px;
  cursor: pointer;
  text-overflow: ellipsis;
  overflow: hidden;
  white-space: nowrap;
}

.context .context_item:hover { background-color: #2ecc71; }

.context .context_item .inner_item { margin: 0px 10px; }

.context .context_item .inner_item i {
  margin: 0 5px 0 0;
  font-weight: bold;
}

.context .context_hr {
  height: 1px;
  border-top: 1px solid #eee;
  margin: 3px 10px;
}

3. Add the following Javascript snippet after the jQuery library to enable the context menu.

$(document).bind("contextmenu", function(event) {
  event.preventDefault();
  $(".context")
    .show()
    .css({
      top: event.pageY + 15, 
      left: event.pageX + 10
    });
});
$(document).click(function() {
  isHovered = $(".context").is(":hover");
  if (isHovered == true) {
    //nothing
  } else {
    $(".context").fadeOut("fast");
  }
});

This awesome jQuery plugin is developed by Vovastradamus. For more Advanced Usages, please check the demo page or visit the official website.