jQuery: custom context menu

A context menu is a GUI menu that appears on a web page when a user clicks with the right button of the mouse on an element. In this post I'm going to show you how to create a custom context menu using the contextmenu event. First of all, let's create a basic image gallery. When a user right-clicks on an image, we'll prompt the link to download the image. Here's our structure:

<div id="gallery">
    <p>Right click on each image to download it</p>
    <img src="http://dev.css-zibaldone.com/onwebdev/post/star-rating/1.jpg" alt="Building 1" />
    <img src="http://dev.css-zibaldone.com/onwebdev/post/star-rating/2.jpg" alt="Building 2" />
    <img src="http://dev.css-zibaldone.com/onwebdev/post/star-rating/3.jpg" alt="Building 3" />
</div>

Some CSS styles, both for the image gallery and for our menus:

#gallery {

    padding: 2em 0;
    width: 70%;
    margin: 0 auto;
    height: 100%;
    overflow: hidden;
    position: relative;
}

#gallery p {

    color: #c40;
    font: 1.5em "Trebuchet MS", Trebuchet, sans-serif;
    margin: 0;
    padding-bottom: 10px;
    text-align: center;
}

#gallery img {

    float: left;
    width: 32%;
    margin-right: 0.5em;
    cursor: pointer;
}

div.context-menu {

    background: #c40;
    color: #fff;
    width: 32%;
    height: 15em;
    line-height: 15em;
    text-align: center;
    border: 2px solid orange;
    border-radius: 10px;
    position: absolute;
}

div.context-menu a {

    color: #fff;
    text-decoration: none;
    font: bold 1em "Trebuchet MS", Trebuchet, sans-serif;
    text-transform: uppercase;
}
div.context-menu a:hover {text-decoration: underline;}

The first thing to do now is to insert a context menu for each image and then hide it:

$(document).ready(function() {

   $('#gallery img').each(function() {

        var contextMenu = '<div class="context-menu">';
        var src = $(this).attr('src');
        var alt = $(this).attr('alt');

        contextMenu += '<a href="' + src + '">' + alt + '</a></div>';

        $(contextMenu).insertAfter($(this)).hide();

   });

   // more code here
});

We create a context menu for each image and then we insert it just after the image itself. Each context menu contains a link that points to the image and has
the alt attribute as its text. Now let's show our context menu:

$('#gallery img').bind('contextmenu', function(e) {

    var imgTop = $(this).position().top;
    var imgLeft = $(this).position().left;

     $(this).next().animate({

        visibility: 'show',
        top: imgTop + 20,
        left: imgLeft + 20

     }, 'slow');

      e.preventDefault();
});

We bind the contextmenu event to each image and at the same time we prevent the default menu from appearing. Each context menu will be absolutely positioned using the image coordinates as reference. You can see a demo below.

Demo

Live demo

This entry was posted in by Gabriele Romanato. Bookmark the permalink.

Comments are closed.