DEV Community

masspopcorn
masspopcorn

Posted on

3

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

AWS GenAI LIVE image

Real challenges. Real solutions. Real talk.

From technical discussions to philosophical debates, AWS and AWS Partners examine the impact and evolution of gen AI.

Learn more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

đź‘‹ Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay