Quick Tip: The HTML5 Context Menu Attribute

In this quick tip I want to talk to you about one of HTML5s hidden beauties, the HTML5 context menu attribute. You have probably never heard of it before, but I assure you it is one of those attributes that could be really useful in certain situations.

What is the HTML5 contextmenu attribute you may ask? Basically, it allows you to add different options to a browsers ‘right-click menu’ with just a few lines of HTML and will even work with Javascript disabled. Although, and very sadly, it currently only works in Firefox.

Let me show you how it works:

html5 Context Menu Demo

Using contextmenu is a lot simpler than you may think. All you need is to add the contextmenu attribute like so:

<section contextmenu="my-right-click-menu"> 
<!-- 
    Add anything you want here
  -->
</section>

As you can see you can add it just like you would add any id or class.

Next we create the menu:

<menu type="context" id="my-right-click-menu">
<!-- 
  Here we will add the new 'right-click' menu items 
  -->
</menu>

As you can see the id of the menu must match the name of the contextmenu, this gives more flexibility allowing you to have more than one menu item on the page within different sections.

Next we will add the menu items. Firstly, I will add one menu item with just plain text and an icon, secondly I will add a link for sharing the current page on Facebook, and the third menu item will be a link for refreshing the page, creating a simple contextmenu with three menu items:

<menu type="context" id="my-right-click-menu">
 <menuitem label="Please do not steal our images" icon="img/forbidden.png"></menuitem>
  <menuitem label="Share on Facebook" onclick="goTo('//facebook.com/sharer/sharer.php?u=' + window.location.href);"></menuitem>
    <menuitem label="Refresh" onclick="window.location.reload()"></menuitem>
  </menu>

You can also create sub menus just by adding another menu tag inside the existing one, like so:

<menu type="context" id="my-right-click-menu">
 <menuitem label="Please do not steal our images" icon="img/forbidden.png"></menuitem>
<menu label="Social Networks">
<menuitem label="Share on Facebook" onclick="window.location.href = 'http://facebook.com/sharer/sharer.php?u=' + window.location.href;"></menuitem>
</menu>
    <menuitem label="Refresh" onclick="window.location.reload()"></menuitem>
  </menu>

As you can see with basic HTML5 you can create something really useful. But please be very careful when using it, as it is currently only supported by Firefox.

Do you have a ‘Quick Tip’ you would like to share with our readers? If so, get in touch with us here: mail@speckyboy.com.

Author: (1 Posts)

Sara is a web designer and developer from Portugal, who happens to love to writing useful and helpful tips. You can visit her at iamsaravieira.com or follow her on Twitter.

Comments