Custom context menu in JS

Learn to code your custom context menu (also referred as right click menu) in JS. In this lesson, we will be covering the mouse events and CSS positions. Watch the below video to learn it now.

Download | Demo

 

Source Code

<!DOCTYPE html>
<html>
	<head>
		<title>Custom context menu (Right-click) in JS</title>
		<style type="text/css">

			*{
				margin: 0;
				padding: 0;
			}

			html, body, .container{
				height: 100%;
			}

			body{
				font-family: verdana;
				font-size: 10px;
			}

			.container{
				background: #f6f6f6;
			}

			.context-menu{
				width: 200px;
				height: auto;
				box-shadow: 0 0 20px 0 #ccc;
				position: absolute;
				display: none;
			}

			.context-menu ul{
				list-style: none;
				padding: 5px 0px 5px 0px;
			}

			.context-menu ul li:not(.separator){
				padding: 10px 5px 10px 5px;
				border-left: 4px solid transparent;
				cursor: pointer;
			}

			.context-menu ul li:hover{
				background: #eee;
				border-left: 4px solid #666;
			}

			.separator{
				height: 1px;
				background: #dedede;
				margin: 2px 0px 2px 0px;
			}

		</style>
	</head>
	<body>
		<div class="container" oncontextmenu="return showContextMenu(event);">
			<div id="contextMenu" class="context-menu">
				<ul>
					<li>Add a event listener</li>
					<li>Disble default behaviour</li>
					<li>Design context menu</li>
					<li>Show the context menu</li>
					<li class="separator"></li>
					<li>Hide on mouse click</li>
					<li>Hide on escape key</li>
				</ul>
			</div>
		</div>
		<script type="text/javascript">

			window.onclick = hideContextMenu;
			window.onkeydown = listenKeys;
			var contextMenu = document.getElementById('contextMenu');

			function showContextMenu (event) {
				contextMenu.style.display = 'block';
				contextMenu.style.left = event.clientX + 'px';
				contextMenu.style.top = event.clientY + 'px';
				return false;
			}

			function hideContextMenu () {
				contextMenu.style.display = 'none';
			}

			function listenKeys (event) {
				var keyCode = event.which || event.keyCode;
				if(keyCode == 27){
					hideContextMenu();
				}
			}

		</script>
	</body>
</html>

Leave a Reply

Your email address will not be published. Required fields are marked *