My Profile Photo

Aravind Vasudevan


An inquisitive polyglot developer and Machine Learning enthusiast.


How to create a context menu using JQuery in 3 steps !

Say Google Drive or WhatsApp web or any other web application with native feel, they all have one thing in common: A Context Menu. A while ago, when I wanted to add one to my web app, like any other programmer, I binged it (:joy:). Jokes Apart, to my surprise, I couldn’t find a single proper tutorial to do that.

After spending a long time searching, I found a couple of StackOverflow answers which were in pure JS and CSS (:confounded:). Hence I created this tutorial explaining how I did it.

Here’s my method of doing this using JQuery & Bootstrap (Basic knowledge of HTML, CSS and JS is enough for this tutorial)


Step 1: Include JQuery and Bootstrap

Copy the below lines to the <head> section.

Step 2: Create a Bootstrap Dropdown Menu

Dropdown Menu in Bootstrap is created by making the class of a <ul> element .dropdown-menu

.context-menu class is created by us using which we’ll add style and script.

Step 3: Add JQuery contextmenu event

Add the contextmenu event to any block element. If you want this to work throughout the page, add the event handler to the html and body.

That’s it!

Here’s the complete solution:

Finally, style the .context-menu to match your site’s theme.

Demo

See the Pen ContextMenu by Aravind (@AravindVasudev) on CodePen.

comments powered by Disqus