How to Create a Right-Click Menu with jQuery?

Estimated read time 2 min read

Here’s an example of how to create a Right-Click Menu with jQuery:

HTML code:

<!DOCTYPE html>
<html>
<head>
	<title>Right-Click Menu with jQuery</title>
	<script src="https://code.jquery.com/jquery-3.6.0.min.js"></script>
	<style>
		.menu {
			position:fixed;
			display:none;
			background-color:#eee;
			border:1px solid #ccc;
			padding:10px;
			z-index:1000;
		}
	</style>
</head>
<body>
	<p>Right-click anywhere on this page to see the menu.</p>
	
	<div class="menu">
		<p><a href="#">Menu Item 1</a></p>
		<p><a href="#">Menu Item 2</a></p>
		<p><a href="#">Menu Item 3</a></p>
	</div>
	
	<script>
		$(document).on("contextmenu", function(event){
			event.preventDefault();
			
			$(".menu").css({
				display: "block",
				left: event.pageX,
				top: event.pageY
			});
		});
		
		$(document).on("click", function(){
			$(".menu").hide();
		});
	</script>
</body>
</html>

In this example, we have a paragraph that tells the user to right-click anywhere on the page to see the menu. We also have a div element with the class “menu” that will contain our menu items.

We also have a script tag where we add our jQuery code. In the script, we listen for a contextmenu event on the document. When the user right-clicks anywhere on the page, we call the preventDefault() method to prevent the default context menu from appearing. Then, we set the display, left, and top CSS properties of the “menu” element to block, event.pageX, and event.pageY, respectively. This will display the menu at the location of the mouse click.

In addition, we listen for a click event on the document. When the user clicks anywhere on the page, we call the hide() method on the “menu” element to hide it again.

Note that in this example, we are using three menu items with links, but you can replace these with your own menu items or other HTML elements as needed.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply