Last Updated: February 25, 2016
·
2.752K
· versatilitywerks

Open context menu on right click, ONLY in certain div

HTML:

<div id='page_wrapper' style='border: 1px solid black; padding: 20px;'>
Right click in this div
</div>
<div id='contextMenu'>
<ul style='list-style: none;'>
<li><a href='#' target='_blank'>Open in New Window</a></li>
<li><a href='#' onclick='window.print()'>Print this Page</a></li>
</ul>
</div>

jQuery

/* Context menu only when you click in #page_wrapper (not in it's children) */
$(document).bind("contextmenu", function(event){
if(event.toElement.id == 'page_wrapper'){
$("#contextMenu").css({"top": event.pageY + "px", "left": event.pageX + "px"}).show();
event.preventDefault();
}
});
$(document).bind('click', function(){
$('#contextMenu').hide();
});