SoFunction
Updated on 2025-04-07

JavaScript Custom Right-click Menu Plugin

This article shares the specific code of the javascript custom right-click menu plug-in for your reference. The specific content is as follows

1. How to use

JS file introduction<script src=""></script>

initialization:

let rightMenu = new RightMenu({
   targetId:'menu',//The element id of the right-click menu needs to be changed   menuItems: items//Menu item data, json array   })

parameter

items = [
 {
 id: 'aa',//Menu id text: 'ccc',//Menu text, can be an html element show: true, //Whether the menu is displayed active: false,//Is the menu available style: 'item-unactive'
 }
]

3. Method

setItems(menuItems) Setting menu. Dynamic Settings Menu

hide() hide menu

on(eventType, event) event listening

4. Events

itemClick menu item click, the callback function parameter is all properties of the menu item

example:

('itemClick',(param) => {
 (param)
 if( === false){
 return
 }
 alert((param))
 // ()
})

createBefore menu content is called before generation, which can realize dynamic menu settings

example:

('createBefore',(param) => {
 (items1)
})

Note: Cascading function is not supported yet

Code:

class RightMenu{
 constructor(param){
  = 
  = ('#' + )
 ( != null, 'not foundid=' +  + 'Elements')
  = null
  = 
 this._menuItems = {}
  = 'item-default'
  = {
 itemClick: null,
 createBefore: null
 }
  = true
 ()
 }
 
 init(){
 let that = this
 ()
  = function(ee) {
 let e = ee || ;
 //Coordinates of mouse point let oX = ;
 let oY = ;
 //The position after the menu appears  = "block";
  = oX + "px";
  = oY + "px";
 ()
 //Block the browser default event return false;//Generally, right-click will appear in the browser's default right-click menu. Writing this code can prevent the default event. }
  = function(ee){
 let e = ee || ;
 if( !==  &amp;&amp;  != 'item'){
  = "none"
 }
 }
  = function(ee) {
 let e = ee || ;
  = "none"
 }
  = function(ee) {
 let e = ee || ;
 if( == 'item'){
 if( instanceof Function){
  (that._menuItems[])
 }
 }
  = true;
 }
  = function(ee){
  = true
 }
  = function(ee){
  = false
 }
 }
 createMenu(){
 if( == null){
  = ('div')
  = 'menu-default'
 ()
 }
 
 let mark = true
 if( instanceof Function){
 mark = ()
 }
 if(mark){
 ()
 }
 }
 _bindOncontextmenu(obj){
  = function(ee){
 ()
 return false
 }
 }
 creatItem(){
 if( == 0){
 return
 }
 let fragement = ()
 let temp = null
 let tempItem = null
 for (let i = 0, len = ; i &lt; len; i++){
 tempItem = [i]
 if( === false){
 continue
 }
 temp = ('div')
  = 
  = 
  =  || 'item-default'
  = 'item'
 
 this._menuItems[] = tempItem
 (temp)
 this._bindOncontextmenu(temp)
 }
  = ''
 (fragement)
 }
 
 on(type,event){
 [type] = event
 }
 
 hide(){
  = 'none'
 }
 
 setItems(items){
  = items
 ()
 }
}

The above is all the content of this article. I hope it will be helpful to everyone's study and I hope everyone will support me more.