DEV Community

masspopcorn
masspopcorn

Posted on

Creating a custom context-menu in JS

Intro

Hey everyone! Have you ever right clicked on a website and were given a nice "right click menu"? Well today I will be showing you how to make one WITH custom CSS!


How do I make this?

To make the menu work, you add in:

 oncontextmenu = (e) => {
  e.preventDefault()
  let menu = document.createElement("div")
  menu.id = "ctxmenu"
  menu.style = `top:${e.pageY-10}px;left:${e.pageX-40}px`
  menu.onmouseleave = () => ctxmenu.outerHTML = ''
  menu.innerHTML = "<p>CTX Menu (with css)</p><p onclick='location.reload()'>Reload</p><p onclick='alert(`Server Status: Running`)'>ServerInfo</p><p onclick=(window.open(`https://patreon.com/masspopcorn`,`_blank`))>đź’¸Donations</p><p onclick='alert(`EVERYBODY DO THE FLOP *flop*`)'>Flop?</p>"
  document.body.appendChild(menu)

Enter fullscreen mode Exit fullscreen mode

To make the design work, you add:

 #ctxmenu {
  border-radius: 4px;
  position: fixed;
  background-color:#39403f;
  color: #FFF;
  cursor: pointer;
  border: 0px black solid
  -webkit-box-shadow: 8px 5px 23px 5px rgba(26,50,71,0.76); 
box-shadow: 8px 5px 23px 5px rgba(26,50,71,0.76);
}

#ctxmenu > p {
  padding: 0 1rem;
  margin: 0
}

#ctxmenu > p:hover {
  background: grey;
  color: ghostwhite
  cursor: crosshair;
}

Enter fullscreen mode Exit fullscreen mode

Outro

Thanks for reading! Here are some links.

Repl Profile: dudeactualdev

Github Profile: dudeactual

Github Repository: CTX-Menu

DEMO: Demo

Top comments (0)