Open context menu on right click in jQuery..but only if you click a 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();
});




Shane Stebner

Author: Shane Stebner

Shane is a successful web-developer specializing in responsive design, and the open-source LAMP stack. Over the years, he's gained in-depth experience with Stripe, Twilio, PhantomJs, Authorize.net, PayPal, Facebook, Twitter, and many other plugins/APIs.


comments powered by Disqus