Navigation Menu

Skip to content

Instantly share code, notes, and snippets.

@hollasch
Last active August 29, 2015 14:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save hollasch/3b37417658474d16fc16 to your computer and use it in GitHub Desktop.
Save hollasch/3b37417658474d16fc16 to your computer and use it in GitHub Desktop.
Right-Click Event Handling in HTML
<!DOCTYPE html> <html lang="en">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Context Menu Handling Example</title>
<style type="text/css">
p { font-family: sans-serif; }
div.text {
margin: 1em auto;
max-width: 40em;
padding: 0.5em 4ex;
}
#div1 {
background-color: #cccc00;
width: 50%;
height: 200px;
margin: 1em auto;
padding: 1em;
}
</style>
<script type="text/javascript">
window.onload = function() {
var div1 = document.querySelector("#div1");
div1.addEventListener('contextmenu', function(event) {
console.log(event);
event.preventDefault();
alert('Got it.');
return false;
}, false);
}
</script>
</head>
<body>
<div class="text">
<p>This simple page demonstrates how to catch and handle right-click (context menu) clicks on
elements in HTML. In general this is not a good idea, as it prevents all of the goodness
normally found in the browser's right-click menu, but when you gotta do it, you gotta do it.</p>
</div>
<div id="div1">
<p>Right-click is handled for this rectangle, and is normal everywhere else on the page.</p>
</div>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment