How to Use the HTML5 Context Menu Attribute


By

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:

Download the Source Files

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>

Download the Source Files

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.


Top
This page may contain affiliate links. At no extra cost to you, we may earn a commission from any purchase via the links on our site. You can read our Disclosure Policy at any time.