jQuery Right-click Plugin

Easily add right-click functionality and disable browser context menus with this lightweight jQuery plugin.

Contents

  1. Overview
  2. Usage
  3. Demo
  4. Compatibility
  5. Change Log
  6. Download
  7. Limitations
  8. Licensing

Overview

This plugin enables you to use jQuery to attach events triggered by the right mouse button. Three right-click events are supported: rightClick, rightMouseUp, and rightMouseDown. There is also a built-in method to disable browser context menus.

Note that for left-handed users the “right” mouse button is actually on the left. The use of “right” and “left” when referring to mouse buttons has become commonplace, therefore it is used as such in this article to prevent confusion.

Usage

$(document).ready( function() {

    // Capture right click
    $("#selector").rightClick( function(e) {
        // Do something
    });
   
    // Capture right mouse down
    $("#selector").rightMouseDown( function(e) {
        // Do something
    });
   
    // Capture right mouseup
    $("#selector").rightMouseUp( function(e) {
        // Do something
    });
   
    // Disable context menu on an element
    $("#selector").noContext();

});

Note: #selector may be any valid jQuery selector.

Demo

Visit the demo page for a full-featured demonstration of this plugin.

Compatibility

This plugin requires jQuery 1.2.6 or higher, and has been tested in the following browsers:

It is worth mentioning that one cannot currently detect a right click nor disable the context menu in Opera 9 or below. Opera 9.5 introduced an option to allow scripts to detect right clicks, but it is disabled by default and the browser’s context menu still cannot be disabled.

Change Log

Version 1.01

Download

Current version: Version 1.01 (20 December 2008)

This plugin is provided to you as-is, at absolutely no cost. If you would like to support its development, feel free to contribute any amount you prefer via PayPal. As always, you are welcome to contribute code for bug fixes and feature enhancements as well. Either way, thanks for supporting our efforts!

Limitations

Multiple Events

You cannot combine a rightClick event with a rightMouseUp event. Most browsers do not return a true click event for the right mouse button. Given that, the plugin simulates a true click by detecting the mousedown and mouseup events. If both occur consecutively on the same element, a click event is fired.

Opera Browsers

Since Opera doesn’t support any of the functionality provided by this plugin, it is best to provide alternative ways for your users to achieve the same results wherever right-click events are used.

Licensing

This plugin is dual-licensed under the GNU General Public License and the MIT License and is copyright 2008 A Beautiful Site, LLC.

Comments

Hi Cory! Great plugin, I was looking for something exactly like this. Most of the other solutions offered context menus but yours is the best for me because it allows one to build on it. thanks

John on Jun 20th, 2008

Hi,
I am not a regular reader of this site but right now it reached my bookmarks. :)
A very nice plug in.
Greetings from Romania.

Mircea Zetea on Jul 12th, 2008

Cool. Thx :)

Mik Shvets on Aug 6th, 2008

Hi Cory,

(I'm new to jquery but...) shouldn't the handler be passed the underlying event, rather than a reference to $(this) ? So as to be consistent with the existing jquery click functions?


Thanks,

Tim

Tim on Aug 18th, 2008

@Tim: good insight Tim, I'll take a look at it soon and update the code as necessary.

Cory S.N. LaViska on Aug 24th, 2008

hi, thanx for your great Plug in, my question is, how can i use Mouse event to receive right clicked zone on my page? The "el" variable doesn't recognize x and y values.

Hell Lord on Aug 31st, 2008

It seems that it doesn't work on firefox 3, any suggestion?

giovanni battista lenoci on Sep 11th, 2008

@Giovanni: it's working fine on my default install of 3.0.1. I would double check the code, particularly your jQuery selector(s) if you're not getting any errors in the console.

Cory S.N. LaViska on Sep 14th, 2008

I'm getting 'Object does not support this property or method'.

I can see the rightClick and noContext functions on the jQuery('.slideable') object but when I call them I get the aforementioned error.

Using IE7. Some of my code is dynamically loaded with eval.

Rob on Nov 13th, 2008

Nice plug-in, and I guess it'll be nicer if you added double-right-click support; what do you think? :)

TheBlueSky on Nov 27th, 2008

Nice plugin - however I'd suggest passing the event across as well:

if( evt.button == 2 ) {
handler( $(this), evt );
return false;
} else {
return true;
}

This means the chained function can also grab values such as pageX and pageY and give you the basis for a custom context menu :)

Obsidian on Dec 2nd, 2008

Cory,

Great plugin, exactly what I was looking for. To keep things consistent with the rest of jQuery, I'd suggest you replace your handler calls. Instead of:

handler( $(this) );

What you probably want is:

handler.call( $(this), e );

This will then call the handler function in the context of the element that fired the event, and pass the event as the first parameter. That way people can still use "$(this)" inside of their callback and it will function as expected.

Thanks again!

Brian Whitmer on Dec 4th, 2008

These are all some very excellent (and educational) comments. I plan on making an update to this plugin this weekend, so be on the lookout for it :)

Cory S.N. LaViska on Dec 4th, 2008

This module is more stable than others even if it doesn't have as many features. I made a few modifications you might find useful.

Line 71
if( o.onShow )o.onShow.call( menu[0] , e );//Callback when the menu is shown so options can be disabled dynamically.

Line 82
$('a:first',menu).focus();//Gives the menu the focus so key events aren't propagated.

Another nice feature would be show the menu on keyboard right-click[keyCode=93].

Kikuchyo on Dec 13th, 2008

Thanks again for all your feedback, everyone. I've released an update that covers most of what everyone was asking for. Please see the 1.01 change log (above) for details.

Cory S.N. LaViska on Dec 20th, 2008

It seems that All-in-One Gestures for Firefox seems to prevent this from working which is a shame. Anyone knows if this works with other gesture extensions on Firefox?

Tatu on Dec 23rd, 2008

@Tatu A better plugin that doesn't conflict is Mouse Gestures Redox (https://addons.mozilla.org/en-US/firefox/addon/39). I saw this same problem with the Context Menu plugin.

Cory S.N. LaViska on Dec 23rd, 2008

The rightClick event does not prevent the default IE context menu from displaying. Even if I call e.preventDefault(); Am I doing something wrong? I'm using jQuery 1.2.6

Keivan S. on Jan 9th, 2009

@Keivan: hmm, haven't seen that on any version of IE. If you want, link me to your page and I'll see if I can reproduce this.

Cory S.N. LaViska on Jan 9th, 2009

Here's a bit more detail. When I right click, I set a div to visible and I lay it where the mouse's x and y coordinates are. This ONLY happens when I do that, otherwise, the IE default context menu doesn't show up.

Keivan S. on Jan 9th, 2009

@Keivan: it sounds like the event might be firing on the DIV. See what happens when you set a delay before making the DIV visible. For example:

[right click event handler here]
setTimeout( function() {
[make DIV visible here]
}, 100);

Cory S.N. LaViska on Jan 9th, 2009

And it seems like that was the case. Thank you.

Keivan S. on Jan 9th, 2009

I'm using the default Firefox 3.0.5 on Ubuntu Linux 8.04 - it all seems to work, except the area that says "no context menu" - I still get a context menu there. Works in IE though.

Costas on Jan 15th, 2009

I have a question about this plugin. What is the purpose of interfering with the normal operation of a user's browser? Is there an example of when this would be needed?

I'm not trying to be a naysayer, or argumentative, but I am truly curious as to why you would "break" a surfer's browser.

why on Feb 8th, 2009

i've got to agree with "why" on this.

i'd also really like to know what a good case is to use this for.

the only thing i could think of is in the case of photography when you don't want people stealing photos off a website, but in that case there are so many ways around right clicking to do it.

so can any of you who have commented give a case where this is actually useful? like "why" here, i am truly curious. not just a jerk. :)

agree on Feb 8th, 2009

In short, this plugin is intended to make life easier for developers to build robust web applications that require user interface elements similar to those found in your average operating system (i.e. context menus). It is not meant to prevent image theft nor to stop people from viewing your source code -- I don't need to mention how silly it is for someone to think that would even be effective.

In all honesty, I wouldn't recommend using this plugin in your average website. If you're not developing a web app, it's probably not for you. If you're developing a kick-ass CMS that needs a custom context menu, this is probably a good place to start.

Cory S.N. LaViska on Feb 8th, 2009

fair enough.

why on Feb 9th, 2009

Hi,

I'm using the "jQuery contextmenu plugin" combined with "jQuery
treeview async plugin". This means that I load in all data into the
treeview from the database. Next step is that I want to be able to
right click these dynamically loaded elements and alert the id of each
element. I get it working in IE, but not in firefox. Any ideas why it
would not work in firefox?

jQuery(document).ready(function(){

jQuery("#black").treeview({
animated: "1",
url: "source.php",
persist: "cookie",
cookieid: "mtree"
});

jQuery('ul li').livequery(function() {
jQuery('span.folder, span.file').contextMenu('theContextMenu', {

bindings: {

'edit': function(t) {

editItem(t.id);

},

'email': function(t) {

alert('Trigger was '+t.id+'\nAction was Email');

},

'save': function(t) {

alert('Trigger was '+t.id+'\nAction was Save');

},

'delete': function(t) {

alert('Trigger was '+t.id+'\nAction was Delete');

}

}

});


});

});

Mike on Feb 9th, 2009

Just wanted to add that the contextmenu does show in firefox as well, but the problem is when i click one of the menu items nothing happens. it's like the bindings don't work..

Mike on Feb 9th, 2009

Hello, thanks for this nice plugin. I'm using it to develop mouse gesture like context menu which reacts when the right mouse is held down and moved.

I've notice the plugin always stops the event. I suggest you change it a bit to stop it only if the handler returns false so users of the plugin can decide what to do themselves.

Also this would be orthogonal to how jquery event handlers work.

Michal Hantl on Feb 17th, 2009

Hi Cory,
Thank you for that plugin, it save my time. But i have a question for you. Rightclick plugin cannot attach to disabled buttons. for example this line of code doesn't work.

<input type="submit" name="ctl00_Mybutton" value="Select" disabled="disabled" id="ctl00_Mybutton" class="MyButton" />

Fatih YASAR on Feb 27th, 2009

@Fatih: I don't believe that events trigger on disabled form controls, so that's most likely the problem.

Cory S.N. LaViska on Feb 28th, 2009

I'm trying to utilize this functionality *only* if there is text selected and pass the selected text to another page. If there's no text selected I'd like to pass the regular event through, but I can't figure out how to do this. Is this possible without a lot of work, or do I need to use jquery.simulate or something?

Any help would be very much appreciated.

$(document).ready(function() {
$("body *").rightMouseUp(function(e) {
if (getSelectedText()) {
document.location = 'contact.aspx?txt=' + encodeURIComponent(getSelectedText()) + '&source=' + document.URL;
} else {
// launch standard right-click event
// here's where I'm stuck
}
});
});

function getSelectedText() {
if (window.getSelection) {
return window.getSelection().toString();
}
else if (document.getSelection) {
return document.getSelection();
}
else if (document.selection) {
return document.selection.createRange().text;
}
}

sean on Mar 2nd, 2009

Hello,

Thanks for this great plugin,

Is any way to make your plugin work on Opera browser?

Kissifrot on Mar 9th, 2009

(except make a rant to Opera devs to enable the option by default ?)

Kissifrot on Mar 9th, 2009

Hi, thx for plugin.

How I can get coordinate when executes mouseUp.

Serg on Mar 13th, 2009

Hi - great plugin - I hope to use it - but the license is the GNU. (Not the MIT and not the LGNU.) Does that mean that all code I write around it also has to be GNU? (I get a bit confused with the GNU used in scripting languages....) Could you clarify? Best wishes.

nick on Mar 15th, 2009

Ah - silly me - not "the GNU" - I meant it is under the GPL, not the LGPL or MIT License. What are the implications of this if I use it with my code for a client?

nick on Mar 15th, 2009

Thx, for plugin.
Add please. At each event returned to the coordinates x, y.

Serg on Mar 23rd, 2009

Like this:

rightMouseUp: function(handler) {
$(this).each( function() {
$(this).mouseup( function(e) {
if( e.button == 2 ) {

// hack
var pos = {layerY: event.layerY, layerX: event.layerX};

handler.call( $(this), e, pos );
return false;
} else {
return true;
}
});
$(this)[0].oncontextmenu = function() {
return false;
}
});
return $(this);
},

Serg on Mar 24th, 2009

Well, talk about evil. Yay for opera not supporting it! Dumb scripts always trying to annoy end users. Stick to standard behaviour so users of your site know what to expect. The only real use of this script is games and "please don't steal images" alert-boxes.
Nice programming job, don't get me wrong, but i dislike the script on principle..

Tom on Mar 24th, 2009

Hi, thanks for this useful plugin.
I was using jquery sortable in my page. After adding right click event of your plugin, it doesn't work :)
What can be the cause? How can I solve this?

Rasit on Apr 2nd, 2009

Nice. I have been trying to make one of these for jQuery.

One problem: it's not cross-browser compatible. Safari < 4, Opera, etc do not work.

I have an alternate version which works in Safari >=2, Opera, etc. Accomplishing this was a major bitch because some browsers only fire a mousedown event on right click, some only fire a contextmenu event, and FireFox fires both events. Here is how I solved it... (not using jQuery, but I'm sure it's adaptable)

var ihaveoncontextmenu = false; //Stop FireFox's double event
var icanseerightclicks = false; //Fix for Safari
function altclick_init() {
document.body.onmousedown = function(e){ if (!ihaveoncontextmenu) { return altclick_event(e); }};
document.body.oncontextmenu = function(e){ if (!icanseerightclicks) { return altclick_event(e, true); } else { return false; }};
}

function altclick_event(e, oncontext){
if (empty(e)) e = window.event;
if (oncontext) {
ihaveoncontextmenu = true;
return handle_altclick(e);
} else if ((e.button == 2)) {
icanseerightclicks = true;
return handle_altclick(e);
}
return true;
}

Also, your font for this site's comment textarea is amazing. Please use it for the actual comment display!

Wes on Apr 7th, 2009

@why

Replacing context menus can be extremely useful when developing an interactive web application.

Contextual menus can be modified for applications that run natively in the operating system; why not modify their functionality for apps run virtually through a web browser?

For example, I made a website which allows you to edit or delete content by right-clicking it and selecting either edit or delete from a custom contextual menu. This keeps the interface clean and simple while utilizing fundamental features of most personal computers today.

Also, it's not our fault that WC3 standards don't allow for simply adding functionality to system context menus. We do what we can.

Wes on Apr 7th, 2009

Seems to me that this should be included with the standard JQuery Library.

conficker on May 12th, 2009

Hi,

How do I unbind the rightClick event handler?

Saugata on May 17th, 2009

This looks like it rightMouseUp event may not fire in a Gecko-based browser on a Mac because of a bug in the button property of mouse events that as far as I know has not yet been fixed: https://bugzilla.mozilla.org/show_bug.cgi?id=264922

I haven't had a chance to verify this yet though.

Tim Down on May 22nd, 2009

Update: Mozilla bug is not marked as fixed but cannot be replicated on my Mac with Firefox 3.

Tim Down on May 22nd, 2009

Thanks thanks thanks. Cool plug-in man. Best regards.

Sedat Kumcu on Jun 21st, 2009

Niiice. Very good and what I was looking for.

Mario Soto on Jun 26th, 2009

It appears the Ubuntu Firefox Modifications pack prevents your plug-in from working with Firefox 3.0.11 and Ubuntu..

Odd but.. there it is.. Simply disabling the plug-in and it works.

palamedes on Jun 26th, 2009

Add a comment

Name*

Email*

Never, ever sold or spammed :)

Homepage

Comment*

Sorry, plain text only :(