Monday, January 31, 2011

Modify right-click menu browser behavior

Recently I've discovered that it's very easy to either completely disable right-click context senstive menus or replace them with a custom dialog. While it's not normally a good idea to remove or change the right-click menu, sometimes it makes sense for a specific application. This post shows how to do it.

To disable the right click menu you need to override a handler of the 'contextmenu' event. With jQuery it's easy, for the page as a whole and for just a particular element:
$(document).bind("contextmenu", function(e) {
return false;
});
$("#rclick-demo").bind("contextmenu", function(e) {
return false;
});

To show custom menu on right click let's define it's structure and style:
<ul id="rclick-menu-id" class="rclick-menu">
<li><a href="#">Edit</a></li>
<li><a href="#">Delete</a></li>
<li><a href="#">Run</a></li>
</ul>

.rclick-menu {
display:none;
font-size:0.75em;
position:absolute;
background:#fff;
border:1px solid #aaa;
}
.rclick-menu ul {
border-right: solid 1px #000;
list-style-type: none;
margin: 0;
padding: 0;
width: 100px;
}
.rclick-menu li {
padding: 0 10px 0 5px;
cursor: pointer;
}

Now we just have to define the 'contextmenu' event handler. It is convenient to do it right after the DOM is ready:
$(document).ready(function() {
$('#rclick-demo').bind('contextmenu', function(e) {
$('.rclick-menu').css({
top: e.pageY+'px',
left: e.pageX+'px'
}).show();
return false;
});
$(document).click(function() {
$('.rclick-menu').hide();
});
});

The second function just hides the menu if you click anywhere beyond its. The 'rclick-demo' id is the following div. So just try how it works:
to view the context menu right click here
In the end I just want to say that actually you don't have to code anything that I have done. Because there is already pretty nice jQuery plugins that can do all the work for you.
http://abeautifulsite.net/blog/2008/09/jquery-context-menu-plugin
http://www.trendskitchens.co.nz/jquery/contextmenu




No comments:

Post a Comment