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:

4 comments:

  1. Hi, Great.. Tutorial is just awesome..It is really helpful for a newbie like me.. I am a regular follower of your blog. Really very informative post you shared here. Kindly keep blogging. If anyone wants to become a Front end developer learn from Javascript Training in Chennai . or Javascript Training in Chennai. Nowadays JavaScript has tons of job opportunities on various vertical industry. ES6 Training in Chennai

    ReplyDelete
  2. Guaranteed #1 Search Engine Ranking Supreme Free Viral Traffic Join Now Get Millions Of Hits Free To Your Site/Blog!

    PornKings Adult Shopping Backlinks-Shopping Mega Store Legendary Stars As Stormy Daniels,Shawna Edwards,Jenna Jamison-New Adult Stars Movies,Adult Toys,Enhancers,Merchandise-More !

    Hits Express Rotator System Do You Need Visitors to Your Website or Affiliate Program? If your looking to gain more visitors to your website Hits Express is your answer. With our program your site is being shown to people all over the world 24/7 365 days a year!

    PAYDIR Free For All Forum Portal Search Engine Crawled Network PR10 Ranking Information Forum XXX!

    FreeLinkExchanges Be Seen In 12 Nations 312 Sites Over 30 Millions Viewers Monthly Buy Featured Link Now With 150 Search Engines Crawling The Network!

    How do I get guaranteed traffic? When someone signs up from your site, they must first click on your classified ad which will open a new window leading to your main website. They will have to wait a few seconds for the code to appear on a separate frame at the top of the screen reach millions free now!

    Blast Your Ad to Over 23,000 Opt-in Prospects at ShowMyLinks Submit Your Solo Email Ad to All Showmylinks Members GET YOUR TEXT LINK ADs LISTED 100% FREE FOR LIFE PLUS EARN MONEY TO YOUR PAYPAL!!

    Adult Store Empires Backlinks Resources Search Engine XXX!

    GET YOUR OWN MONEY-MAKING AD BOARD -- Integrating Text ad, Banner Ad and Email Ad into one Portal Make Money Fast With Your Paypal Reach Million Dollars In A Year Fast !

    Full Length Homemade Videos Watch real people's private home sex videos. Forget about those shitty 1-2 minute clips, these are all high quality full length videos! 40+ Bonus Sites You will also get full access to the entire reelpass network of sites which features over 40+ awesome movie sites, 1000's of movies and pictures to download! Download, Burn & Share Not only do you get to watch all our movies, you can also download every single one and save it forever, burn them to dvd or share with friends!!

    ReplyDelete

Thanks a lot for your valuable comments :)