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>
		<title>Custom context menu (Right-click) in JS</title>
		<style type="text/css">

				margin: 0;
				padding: 0;

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

				font-family: verdana;
				font-size: 10px;

				background: #f6f6f6;

				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;

				height: 1px;
				background: #dedede;
				margin: 2px 0px 2px 0px;

		<div class="container" oncontextmenu="return showContextMenu(event);">
			<div id="contextMenu" class="context-menu">
					<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>
		<script type="text/javascript">

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

			function showContextMenu (event) { = 'block'; = event.clientX + 'px'; = event.clientY + 'px';
				return false;

			function hideContextMenu () { = 'none';

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


Leave a Reply

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