javascript Right-Click Menu
This article is automatically translated by LLM, so the translation may be inaccurate or incomplete. If you find any mistake, please let me know.
You can find the original article here .
In my spare time, I tried to implement a simple right-click menu using pure JavaScript. Although I didn't use any complex CSS and the appearance is quite ugly, it is basically functional.
Example
~~Some of the CSS is actually imitating Bootstrap~~
Initialization
const ctxmenu = document.querySelector('.ctxmenu') //選單元素
const baseEL = document.querySelector('.box') //要自訂選單的元素
Handling Events
Displaying the Menu
In simple terms, it involves moving the menu to the position of the event and then displaying it.
It is also very important to call the stopPropagation()
function, which is related to what we do later.
baseEL.addEventListener('contextmenu', e => {
e.preventDefault()
e.stopPropagation() //important!!
//move element
ctxmenu.style.top = e.y + 'px'
ctxmenu.style.left = e.x + 'px'
//show element
ctxmenu.classList.add('show')
})
Canceling the Menu
Here you will see that both contextmenu
and click
do the same thing, which is to hide the menu.
If stopPropagation()
was not called in the previous step, clicking on the specified element would also remove the show
class.
document.addEventListener('contextmenu', e => {
ctxmenu.classList.remove('show')
})
document.addEventListener('click', e => {
ctxmenu.classList.remove('show')
})