New Revised CSS Library Forums Web Tools
FAQs Awards Usage Terms Contact
Other Sections
Bookmark to

FF1+ IE5+

jQuery Context Menu script

Author: Dynamic Drive

Note: Script completely rewritten Dec 16th 2009'

Description: This jQuery script lets you associate a multi-level context menu to any element on the page, so right clicking within the element activates the menu. The default context menu of the browser is suppressed as a result. A different context menu can be added to different elements on the page, such as one for the document as a whole, another for just a DIV on the page etc.

Note that Opera as of Opera 10 does not yet support replacing the browser's default context menu with a custom one, and hence this script will not work in it.

Demo (right click inside the below two elements, or any image on this page for that matter):

Dynamic Drive

Here we've defined two context menus, one associated with a specific link, the other, all images on the page.

Directions Developer's View

Step 1: This script uses three external files, including an image. Download them below (right click, and select "Save As"):

Step 2: Add the below code to the HEAD section of your page:

Select All

Step 2: Having done the above, add the below sample HTML to the BODY of your page, which contains a link and an image, plus two context menus associated with them:

Select All

More Set up information

To create a context menu and associate it with a specific element on your page, first, define the HTML markup for the menu anywhere on your page. The markup should be a regular UL list with a unique but arbitrary ID attribute plus a CSS class of "jqcontextmenu". For example:

<ul id="contextmenu2" class="jqcontextmenu">
<li><a href="#">Item 1a</a></li>
<li><a href="#">Item 2a</a></li>
<li><a href="#">Item 1a</a></li>
<li><a href="#">Item 2a</a></li>

With the markup for the context menu defined, to associate it with an element on the page, inside the HEAD section of your page, call the method:


Where "elementselector" is a valid jQuery element selector, and "contextmenuid" is obviously the ID of the context menu it should be associated with the matched elements. Lets say you want to associate the above context menu to all images on your page. The syntax would be:

 $('img').addcontextmenu('contextmenu2') //apply context menu to all images on the page

The extra surrounding code is to call the method only when the page has loaded. How about adding a context menu to the entire document?

 $(document).addcontextmenu('contextmenu2') //apply context menu to all images on the page

Or maybe all links on the page with CSS class "mylinks":

 $('a.mylinks').addcontextmenu('contextmenu2') //apply context menu to all images on the page

You get the idea!