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
</pre>


<script>

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

    try
    {
        // 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
    window.getSelection().removeAllRanges();
};


</script>


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


Author

Programster

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

comments powered by Disqus