Creating Custom Context Menu Using jQuery

Introduction

Hello readers, in this article I'm going to tell you something amazing. You can customize your website in many ways, but have you ever thought of creating your own customized right-click menu. Yes! I'm talking about right-click menu or context menu. It's very easy and in this article we will also develop one. It can be very useful in various situations, like when the user clicks on an image of your website and you want to show various options other than the default ones. This article will help you with that.

Logic behind the menu

The logic is quite simple. As I always say, we need to examine the things carefully if we want to understand them. This logic is derived from that principle only. To understand the logic, let us first analyse the default context menu. We can analyze it in the following step-by-step manner:

  1. The user right-clicks on a web page to open the context menu.
  2. After right-clicking a new box opens up.

    img1.PNG

     
  3. That box contains some item lists.

    img2.PNG

     
  4. On clicking those items, the following two things happen
  5. The Box is hidden and the operations are performed.
  6. Another thing to notice is that if a click is done somewhere else then the box is also closed.
  7. If the user does another right-click without closing the first one then the first box is automatically closed and the new one is opened.
  8. The box is always opened at the mouse location.

So after reading the above analysis it is easy to understand the rest of the logic. So let's proceed to our jQuery based context menu logic as in the following:

  1. The box is nothing but just a div. So we will create a div for representing that box.
  2. The items in the box are similar to the lists we have in our HTML, the <LI> tag.
  3. Opening and closing can be done using Hide and Fade In functions.
  4. Item clicks can be processed by registering the click event on list items.
  5. The minor optimization will be clear from the code itself.

Coding the Context Menu

It's time to convert our logic into code. First we need to write the HTML. Just paste the following code snippet in a HTML file.

  <span id="op">Demo</span> // For showing output.
  <div id='cntnr'>                         // Context menu container.
    <ul id='items'>                        // List of items in context menu.  
      <li>Item1</li>                      // Items to show in context menu.
      <li>Item2</li>
      <li>Item3</li>
      <li>Item4</li>
      <li>Item5</li>
    </ul>
  </div>

To design our context menu we need some CSS as well. So here it is.

     #items
      {
          list-style: none;      // For removing the list styling.
          padding: 0px;
          margin: 5px 0 0 5px;
          font-size: 20px;       // setting fonts
      }
      #cntnr
      {
          display: none;        // initially hidden.
          position: fixed;      
          border: 1px solid grey;
          width: 150px;
          background: url("http://cdn.freebievectors.com/illustrations/12/d/dynamic-brilliant-stereo-effects-figure-vector/small-thumb.jpg"); // Context menu background
          box-shadow: 2px 2px 1px grey;  //adding small drop shadow
      }
      li
      {
          border-bottom: 1px solid grey;  //for separating bottom border
          border-bottom-style: dotted;
      }
      #items :hover                       //to add hover effect.
      {
          background: grey;    
          color: white;
      }

It's time to make the things realistic, it's time to add some jQuery.
            $(document).bind("contextmenu", function (e) {
            e.preventDefault();                 // To prevent the default context menu.
            $("#cntnr").css("left", e.pageX);   // For updating the menu position.
            $("#cntnr").css("top", e.pageY);    //
            $("#cntnr").fadeIn(500, startFocusOut()); //  For bringing the context menu in picture.
        });
        function startFocusOut() {
            $(document).on("click", function () {  
                $("#cntnr").hide(500);              // To hide the context menu
                $(document).off("click");          
            });
        }
        $("#items > li").click(function () {
            $("#op").text("You have selected " + $(this).text());  // Performing the selected function.
        });

The code above is very simple.  We are binding the context menu listener to the document first so that we can handle it. The startFocusOut() function is used for monitoring the focus lost or to monitor the off menu click. If that click is done then the context menu will be hidden. The click listener on a list item is used to do the selected operation.

Output

The following shows the opening of the Context Menu:
 

 op1.PNG


The following shows the closing of the Context Menu:
 

op2.PNG


The following shows the selection of an item from the Context Menu:
 

op3.PNG
 


The following shows the performance of the selected operation:

 

op4.PNG
 


Summary

Thanks for reading my article. You can also have more than one context menu in a same page. How? Just think and comment with your solution. In case of any doubt, you can use the comment section.

Don't forget to like and share this article.