1oncontextmenu = (e) => {
2 e.preventDefault()
3 let menu = document.createElement("div")
4 menu.id = "ctxmenu"
5 menu.style = `top:${e.pageY-5}px;left:${e.pageX-5}px`
6 menu.onmouseleave = () => ctxmenu.outerHTML = ''
7 menu.innerHTML = "<p>Option1</p><p>Option2</p><p>Option3</p><p>Option4</p><p onclick='alert(`Thank you!`)'>Upvote</p>"
8 document.body.appendChild(menu)
9}
1<!DOCTYPE html>
2<html lang="en">
3 <head>
4 <meta charset="UTF-8" />
5 <title>Custom Right Click Menu</title>
6 <meta name="viewport" content="width=device-width, initial-scale=1.0" />
7 <meta https-equiv="X-UA-Compatible" content="ie=edge" />
8 <link rel="stylesheet" href="style.css" />
9 <link rel="preconnect" href="https://fonts.gstatic.com">
10 <link href="https://fonts.googleapis.com/css2?family=Montserrat:wght@300;400;500;700&display=swap" rel="stylesheet">
11 <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
12 </head>
13 <body>
14 <div id="contextMenu" class="context-menu" style="display: none">
15 <ul class="menu">
16 <li class="share"><a href="#"><i class="fa fa-share" aria-hidden="true"></i> Share</a></li>
17 <li class="rename"><a href="#"><i class="fa fa-pencil" aria-hidden="true"></i> Rename</a></li>
18 <li class="link"><a href="#"><i class="fa fa-link" aria-hidden="true"></i> Copy Link Address</a></li>
19 <li class="copy"><a href="#"><i class="fa fa-copy" aria-hidden="true"></i> Copy to</a></li>
20 <li class="paste"><a href="#"><i class="fa fa-paste" aria-hidden="true"></i> Move to</a></li>
21 <li class="download"><a href="#"><i class="fa fa-download" aria-hidden="true"></i> Download</a></li>
22 <li class="trash"><a href="#"><i class="fa fa-trash" aria-hidden="true"></i> Delete</a></li>
23 </ul>
24 </div>
25
26 <script>
27 document.onclick = hideMenu;
28 document.oncontextmenu = rightClick;
29
30 function hideMenu() {
31 document.getElementById("contextMenu")
32 .style.display = "none"
33 }
34
35 function rightClick(e) {
36 e.preventDefault();
37
38 if (document.getElementById("contextMenu") .style.display == "block"){
39 hideMenu();
40 }else{
41 var menu = document.getElementById("contextMenu")
42 menu.style.display = 'block';
43 menu.style.left = e.pageX + "px";
44 menu.style.top = e.pageY + "px";
45 }
46 }
47 </script>
48 </body>
49</html>