Wednesday, July 8, 2009

JavaScript Context Menu

Apart from regular event handlers like mouse and keyboard events, the DOM-compliant browsers also provides a contextmenu event to specifically indicate when context menu is about to be displayed. This allows you to cancel the default context menu and provide you own menu to the users. Your personal context menu will be very helpful to your visits for navigation on your website. Here is a sample of how the context menu would look like:
JavaScript Context MenuFor event handing I have used the code from my previous post on Cross-Browser Event Handler. Rest of the code for contextmenu event is pretty straight-forward and easy to modify. Two events are added to the page when it loads for the first time; first one to display the context menu and second one to close the context menu when the user clicks anywhere else on the window. Here is the complete JavaScript code for the context menu:

<script type="text/javascript">
var EventUtil = {
      addHandler: function(element, type, handler){
            if (element.addEventListener){
                  element.addEventListener(type, handler, false);
            } else if (element.attachEvent){
                  element.attachEvent("on" + type, handler);
            } else {
                  element["on" + type] = handler;
            }
      },
      removeHandler: function(element, type, handler){
            if (element.removeEventListener){
                  element.removeEventListener(type, handler, false);
            } else if (element.detachEvent){
                  element.detachEvent("on" + type, handler);
            } else {
                  element["on" + type] = null;
            }
      },
      getEvent: function(event){
            return event ? event : window.event;
      },    
      getTarget: function(event){
            return event.target || event.srcElement;
      },
      preventDefault: function(event){
            if (event.preventDefault){
                  event.preventDefault();
            } else {
            event.returnValue = false;
            }
      },
      stopPropagation: function(event){
            if (event.stopPropagation){
                  event.stopPropagation();
            } else {
                  event.cancelBubble = true;
            }
      }
};

// Add contextmenu event to document on page load
EventUtil.addHandler(window, "load", function(event){
      // Add contextmenu event to document
      EventUtil.addHandler(document, "contextmenu", function(event){
            EventUtil.preventDefault(event); // Prevent default context menu
            var menu = document.getElementById("ContextMenu");
            menu.style.left = event.clientX + "px"; //Context Menu X location
            menu.style.top = event.clientY + "px"; //Context Menu Y location
            menu.style.visibility = "visible";  //Make Context Menu visible
      });
      // Add click event to document for closing contextmenu
      EventUtil.addHandler(document, "click", function(event){
            // Hide Context Menu
            document.getElementById("ContextMenu").style.visibility = "hidden";
      });
});
</script>

Here is the CSS Code for the Context Menu. You can modify the Menu CSS to match the color and styling of your website:

<style type="text/css">
<!--
#ContextMenu {
      position: absolute;
      visibility: hidden;
      margin: 0px;
      padding: 0px;
      border: 3px outset #E4E4E4;
}
#ContextMenu li{
      list-style-image: none;
      list-style-type: none;
}
#ContextMenu li a{
      font-family: Verdana, Geneva, sans-serif;
      font-size: small;
      color: #333;
      padding-top: 2px;
      padding-right: 20px;
      padding-bottom: 2px;
      padding-left: 20px;
      display: block;
      text-decoration: none;
      cursor: default;
}
#ContextMenu li a:hover{
      background-color: #E4E4E4;
}
#ContextMenu li.divider{
      border: 1px solid #DDD;
      margin: 2px;
}
-->
</style>

Put the JavaScript and CSS code inside the head section of your HTML page.

The HTML code for the context menu is simply an unordered list (ul) of links. To insert divider between the menu items you can simply use a list item (li) with divider class as shown below. I have created links for some of the basic functionalities on a webpage context menu like back, forward and refresh. For adding new items to the menu simply add a link inside a new list item. The HTML code for your context menu can be placed anywhere inside the HTML page body:

<ul id="ContextMenu">
      <li><a href="javascript:history.go(-1)">Back</a></li>
      <li><a href="javascript:history.go(1)">Forward</a></li>
      <li><a href="javascript:location.reload(true)">Refresh</a></li>
      <li class="divider"></li>
      <li><a href="">My Homepage</a></li>
      <li><a href="">My Blog</a></li>
      <li><a href="">My Link 1</a></li>
      <li><a href="">My Link 2</a></li>
      <li class="divider"></li>
      <li><a href="mailto:youremail@mail.com">Email me</a></li>
</ul>

Note: This DOM event may not be supported by all the browsers.

Technorati Tags:

2 comments:

Thanks a lot for your valuable comments :)