HTML5 - Context Menus

One of the great additions in HTML5 was the ability to add to the context menu when the user right clicks something. Not all browsers support this (such as Chromium and Opera), but it will work in Firefox.

Below is a code example which will use a context menu to copy to clipboard, which itself can be right clicked for the option menu to copy to clipboard.

<pre id="code-to-<pre id="code-to-copy" contextmenu="menu">  
// This is some code
// Another line


var copyCodeFunction = function(event)  
    // Select the pre text  
    var code = document.querySelector('#code-to-copy');
    var range = document.createRange();

        // Now that we've selected the anchor text, execute the copy command
        var successful = document.execCommand('copy');
        var msg = successful ? 'successful' : 'unsuccessful';
        console.log('Copy email command was ' + msg);
    catch (err)
        console.log('Oops, unable to copy');

    // Remove the selections - NOTE: Should use
    // removeRange(range) when it is supported


<!-- Add the right click context menu to copy code -->
<menu type="context" id="menu">
    <menuitem label="Copy To Clipboard" onCLick="copyCodeFunction();"></menuitem>



Stuart is a software developer with a passion for Linux and open source projects.

comments powered by Disqus
We are a participant in the Amazon Services LLC Associates Program, an affiliate advertising program designed to provide a means for us to earn fees by linking to and affiliated sites. More info.