Example code of layim integrating right-click menu in JavaScript

Example code of layim integrating right-click menu in JavaScript

1. Effect Demonstration

1.1、Friends right-click menu:

insert image description here

1.2. Group right-click menu:

insert image description here

1.3. Group right-click menu:

insert image description here

2. Implementation Tutorial

Next, we take the friend right-click menu as an example, the implementation steps are as follows:

2.1. Bind friend right-click event:

/* Bind friend right click event */
$('body').on('mousedown', '.layim-list-friend li ul li', function(e){
 // Filter non-right-click events if(3 != e.which) {
 	return;
 }
	// Stop dispatching events e.stopPropagation();
	
	var othis = $(this);
 // Get the friend number to facilitate the use of functions later (you need to modify the layim.js source code to bind the friend number; or directly intercept the friend number in the class, which can be viewed by pressing F12 on the page)
	var mineId = $(this).data('mineid');
	var uid = Date.now().toString(36);
	var space_icon = '  ';
	var space_text = '      ';
	var html = [
			'<ul id="contextmenu_'+uid+'" data-id="'+mineId+'" data-index="'+mineId+'" data-mold="1">',
			'<li data-type="menuChat"><i class="layui-icon" >&#xe611;</i>'+space_icon+'Send instant message</li>',
			'<li data-type="menuProfile"><i class="layui-icon">&#xe60a;</i>'+space_icon+'View profile</li>',
			'<li data-type="menuHistory"><i class="layui-icon" >&#xe60e;</i>'+space_icon+'Message History</li>',
			'<li data-type="menuDelete">'+space_text+'Delete friends</li>',
			'<li data-type="menuMoveto">'+space_text+'Move to</li></ul>'
		].join('');
	// Pop-up window layer.tips(html, othis, {
  	Tips: 1
  	,time: 0
  	,shift: 5
  	,fix: true
  	,skin: 'ayui-box layui-layim-contextmenu'
 });
});

The right-click event has been successfully bound here, but the pop-up window directly blocks the friend's name and avatar, which is not very friendly. How to optimize it? Let's continue reading.

insert image description here

2.2. Reset the pop-up window position:
Next, we reset the pop-up box position in the successful callback method after the layer pops up. Based on the default pop-up box position, we move it to the left by a certain number of pixels, and dynamically move it downward according to the number of li in the pop-up box. If it is a pop-up box at the bottom of the reply, the pop-up box moves upward as a whole.

layer.tips(html, othis, {
 	Tips: 1
 	,time: 0
 	,shift: 5
 	,fix: true
 	,skin: 'ayui-box layui-layim-contextmenu'
 	,success: function(layero){
 		// -----#Start---------- Reset the pop-up window position----------------
 	var stopmp = function (e) { stope(e); };
 	layero.off('mousedowm',stopmp).on('mousedowm',stopmp);
 	var layerobj = $('#contextmenu_'+uid).parents('.layui-layim-contextmenu');
 		// Get the number of right-click box li var liCount = (html.split('</li>')).length;
 	 // Get the original pop-up box position var top = layerobj.css('top').toLowerCase().replace('px','');
		var left = layerobj.css('left').toLowerCase().replace('px','');
		// Position personality adjustment top = getTipTop(1, top, liCount);
		left = 30 + parseInt(left);
 	// Move the bullet box position layerobj.css({'width':'150px', 'left':left+'px', 'top':top+'px'});
		$('.layui-layim-contextmenu li').css({'padding-left':'18px'});
 		// -----#End---------- Reset the pop-up window position----------------
 	}
});

// Get the height of the document display area of ​​the window var currentHeight = getViewSizeWithScrollbar();
function getViewSizeWithScrollbar(){
	var clientHeight = 0;
	if(window.innerWidth){
		clientHeight = window.innerHeight;
	}else if(document.documentElement.offsetWidth == document.documentElement.clientWidth){ 
		clientHeight = document.documentElement.offsetHeight;
	}else{ 
		clientHeight = document.documentElement.clientHeight + getScrollWith();
	} 
	clientHeight = clientHeight - 180;
	return clientHeight;
}

/**
 * Calculate the tip location height * @param type type (1 friend, group, 2 group)
 * @param top original bullet frame height* @param liCount number of li in the bullet frame layer*/
var getTipTop = function (type, top, liCount) {
	liCount--;
	if(top > (currentHeight-45*liCount)){
		top = parseInt(top) - 45;
	}else{
		if(type == 1){
			top = parseInt(top) + 30*liCount - 10;
		}else{
			top = parseInt(top) + 30*(liCount - 1);
		}
	}
	return top;
};

After resetting the position of the pop-up frame, it looks much more beautiful as shown in the picture.

insert image description here

2.3. Optimize the right-click pop-up event:
When the user operates other functions, the right-click pop-up window layer still exists in the interface. In order to improve the user experience, the following monitors mouse events and mouse wheel events to close the right-click pop-up window layer in time.

// Prevent the browser from right-clicking by default document.oncontextmenu = function() {
 return false;
}
// Click the chat main interface event $('body').on('click', '.layui-layim', function(e){
 emptyTips();
});
// Right click chat main interface event $('body').on('mousedown', '.layui-layim', function(e){
 emptyTips();
});
// Listen for mouse wheel events $('body').on('mousewheel DOMMouseScroll', '.layim-tab-content', function(e){
 emptyTips();
});
// Clear all right-click pop-ups var emptyTips = function () {
	// Close the right-click menu layer.closeAll('tips');
};

2.4. Bind the click event of the option in the right-click menu:
The last step is to bind the click event of the options in the right-click menu, taking "Send Instant Message" as an example.

var $ = layui.jquery, active = {
	menuChat: function(){
		/*Send an instant message*/
	 var mineId = $(this).parent().data('id');
	 var moldId = $(this).parent().data('mold');
		console.log(mineId);
	 layim.chat({
			type: moldId == 1 ? "friend" : "group",
	 	name: 'Xiao Huan',
			avatar: 'Friend avatar, actual application dynamic binding',
			id: mineId,
			status: 'Friend's current offline status'
		});
 },
 menuHistory: function(){
 	/*Message record*/
		var mineId = $(this).parent().data('id');
	 var moldId = $(this).parent().data('mold');
		console.log(mineId);
 }
};
$('body').on('click', '.layui-layer-tips li', function(e){
 var type = $(this).data('type');
 active[type] ? active[type].call(this) : '';
	// Clear all right-click pop-up boxes emptyTips();
});

Congratulations, you're done!

3. Finally, attach the complete code

// Prevent the browser from right-clicking by default document.oncontextmenu = function() {
 return false;
}
// Click the chat main interface event $('body').on('click', '.layui-layim', function(e){
 emptyTips();
});
// Right click chat main interface event $('body').on('mousedown', '.layui-layim', function(e){
 emptyTips();
});
/* Listen for mouse wheel events*/
$('body').on('mousewheel DOMMouseScroll', '.layim-tab-content', function(e){
 emptyTips();
});
/* Bind friend right click event */
$('body').on('mousedown', '.layim-list-friend li ul li', function(e){
	// Clear all right-click pop-up boxes emptyTips();
 if(3 != e.which) {
 	return;
 }
	// Stop dispatching events e.stopPropagation();
	
	var othis = $(this);
 if (othis.hasClass('layim-null')) return;
 
	// Remove all selected styles $('.layim-list-friend li ul li').removeAttr("style","");
 // Mark as selected othis.css({'background-color':'rgba(0,0,0,.05)'});
 
	var mineId = $(this).data('mineid');
	var uid = Date.now().toString(36);
	var space_icon = '&nbsp;&nbsp;';
	var space_text = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
 var html = [
  			'<ul id="contextmenu_'+uid + '" data-id="'+mineId+'" data-index="'+mineId+'" data-mold="1">',
  			'<li data-type="menuChat"><i class="layui-icon" >&#xe611;</i>'+space_icon+'Send instant message</li>',
  			'<li data-type="menuProfile"><i class="layui-icon">&#xe60a;</i>'+space_icon+'View profile</li>',
  			'<li data-type="menuHistory"><i class="layui-icon" >&#xe60e;</i>'+space_icon+'Message History</li>',
  			'<li data-type="menuDelete">'+space_text+'Delete friends</li>',
  			'<li data-type="menuMoveto">'+space_text+'Move to</li></ul>'
  		].join('');
 
 layer.tips(html, othis, {
  	Tips: 1
  	,time: 0
  	,shift: 5
  	,fix: true
  	,skin: 'ayui-box layui-layim-contextmenu'
  	,success: function(layero){
  	 var liCount = (html.split('</li>')).length;
  	var stopmp = function (e) { stope(e); };
  	layero.off('mousedowm',stopmp).on('mousedowm',stopmp);
  	var layerobj = $('#contextmenu_'+uid).parents('.layui-layim-contextmenu');
  	// Move the pop-up box position var top = layerobj.css('top').toLowerCase().replace('px','');
 			var left = layerobj.css('left').toLowerCase().replace('px','');
 			top = getTipTop(1, top, liCount);
 			left = 30 + parseInt(left);
 			layerobj.css({'width':'150px', 'left':left+'px', 'top':top+'px'});
 			$('.layui-layim-contextmenu li').css({'padding-left':'18px'});
  	}
	});
});

// Clear all right-click pop-ups var emptyTips = function () {
	// Remove the styles selected by all friends $('.layim-list-friend li ul li').removeAttr("style", "");
	// Remove the selected styles of all groups $('.layim-list-group li').removeAttr("style","");
	// Close the right-click menu layer.closeAll('tips');
};

// Get the height of the document display area of ​​the window var currentHeight = getViewSizeWithScrollbar();
function getViewSizeWithScrollbar(){
	var clientHeight = 0;
	if(window.innerWidth){
		clientHeight = window.innerHeight;
	}else if(document.documentElement.offsetWidth == document.documentElement.clientWidth){ 
		clientHeight = document.documentElement.offsetHeight;
	}else{ 
		clientHeight = document.documentElement.clientHeight + getScrollWith();
	} 
	clientHeight = clientHeight - 180;
	return clientHeight;
}

/**
 *Calculate the height of the tip location* @param type type (1 friend, group, 2 group)
 * @param top original bullet frame height* @param liCount number of li in the bullet frame layer*/
var getTipTop = function (type, top, liCount) {
	liCount--;
	if(top > (currentHeight-45*liCount)){
		top = parseInt(top) - 45;
	}else{
		if(type == 1){
			top = parseInt(top) + 30*liCount - 10;
		}else{
			top = parseInt(top) + 30*(liCount - 1);
		}
	}
	return top;
};

// Bind the click event of the right-click menu option var $ = layui.jquery, active = {
	menuChat: function(){
		/*Send an instant message*/
	 var mineId = $(this).parent().data('id');
	 var moldId = $(this).parent().data('mold');
		console.log(mineId);
	 layim.chat({
			type: moldId == 1 ? "friend" : "group",
	 	name: 'Xiao Huan',
			avatar: 'Friend avatar, actual application dynamic binding',
			id: mineId,
			status: 'Friend's current offline status'
		});
 },
 menuHistory: function(){
 	/*Message record*/
		var mineId = $(this).parent().data('id');
	 var moldId = $(this).parent().data('mold');
		console.log(mineId);
 }
};
$('body').on('click', '.layui-layer-tips li', function(e){
 var type = $(this).data('type');
 active[type] ? active[type].call(this) : '';
	// Clear all right click pop-ups emptyTips();
});

4. Other right-click menu code extensions

4.1、Group right-click menu:

/* Bind group right click event */
$('body').on('mousedown', '.layim-list-friend li h5', function(e){
	// Clear all right-click pop-up boxes emptyTips();
 if(3 != e.which) {
 	return;
 }
	// Stop dispatching events e.stopPropagation();
	
	var othis = $(this);
 if (othis.hasClass('layim-null')) return;
 
 var groupId = othis.data('groupid');
	var uid = Date.now().toString(36);
	var space_icon = '&nbsp;&nbsp;';
	var space_text = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	
	var html = [
  			'<ul id="contextmenu_'+uid+'" data-id="'+groupId+'" data-index="'+groupId +'">',
  			'<li data-type="menuReset"><i class="layui-icon" >&#xe669;</i>'+space_icon+'Refresh friend list</li>',
  			// '<li data-type="menuOnline"><i class="layui-icon">&#x1005;</i>'+space_icon+'Show online friends</li>',
  			'<li data-type="menuInsert">'+space_text+'Add group</li>',
  			'<li data-type="menuRename">'+space_text+'Rename</li>',
  			'<li data-type="menuRemove" data-mold="1">'+space_text+'Delete group</li></ul>',
  		].join('');
	
 layer.tips(html, othis, {
 	Tips: 1
 	,time: 0
 	,shift: 5
 	,fix: true
 	,skin: 'ayui-box layui-layim-contextmenu'
 	,success: function(layero){
 	 var liCount = (html.split('</li>')).length;
	  	var stopmp = function (e) { stope(e); };
	  	layero.off('mousedowm',stopmp).on('mousedowm',stopmp);
	  	var layerobj = $('#contextmenu_'+uid).parents('.layui-layim-contextmenu');
	  	// Move the pop-up box position var top = layerobj.css('top').toLowerCase().replace('px','');
			var left = layerobj.css('left').toLowerCase().replace('px','');
			top = getTipTop(2, top, liCount);
			left = 30 + parseInt(left);
			layerobj.css({'width':'150px', 'left':left+'px', 'top':top+'px'});
			$('.layui-layim-contextmenu li').css({'padding-left':'18px'});
 	}
 });
});

4.2. Right-click menu in the blank area of ​​the friend list:

/* Bind right-click event to blank area in friend list */
$('body').on('mousedown', '.layim-list-friend', function(e){
	// Clear all right-click pop-up boxes emptyTips();
 if(3 != e.which) {
 	return;
 }
	// Stop dispatching events e.stopPropagation();

	var othis = $(this);
 if (othis.hasClass('layim-null')) return;
  
	var uid = Date.now().toString(36);
	var space_icon = '&nbsp;&nbsp;';
	var space_text = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	var html = [
  			'<ul id="contextmenu_'+uid+'">',
  			'<li data-type="menuReset"><i class="layui-icon" >&#xe669;</i>'+space_icon+'Refresh friend list</li>',
  			'<li data-type="menuInsert">'+space_text+'Add group</li></ul>',
  		].join('');
  
 layer.tips(html, othis, {
 	Tips: 1
 	,time: 0
 	,shift: 5
 	,fix: true
 	,skin: 'ayui-box layui-layim-contextmenu'
 	,success: function(layero){
 	 var liCount = (html.split('</li>')).length;
	  	var stopmp = function (e) { stope(e); };
	  	layero.off('mousedowm',stopmp).on('mousedowm',stopmp);
	  	var layerobj = $('#contextmenu_'+uid).parents('.layui-layim-contextmenu');
	  	var top = e.pageY;
	  	var left = e.pageX;
	  	var screenWidth = window.screen.width;
	  	// Adjust the position according to the entity situation if(screenWidth-left > 150){
	  		left = left - 30;
	  	}else if(screenWidth-left < 110){
	  		left = left - 180;
	  	}else{
	  		left = left - 130;
	  	}
	  	if(top > 816){
				top = top - 140;
	  	}else{
				top = top - 60;
	  	}
			layerobj.css({'width':'150px', 'left':left+'px', 'top':top+'px'});
			$('.layui-layim-contextmenu li').css({'padding-left':'18px'});
 	}
 });
}); 

insert image description here

4.3. Group right-click menu:

/* Bind group chat right click event*/
$('body').on('mousedown', '.layim-list-group li', function(e){
	// Clear all right-click pop-up boxes emptyTips();
 if(3 != e.which) {
 	return;
 }
	// Stop dispatching events e.stopPropagation();
	
	var othis = $(this);
 if (othis.hasClass('layim-null')) return;
  
	// Remove all selected styles $('.layim-list-group li').removeAttr("style","");
 // Mark as selected othis.css({'background-color':'rgba(0,0,0,.05)'});
	
	var mineId = $(this).data('mineid');
	var uid = Date.now().toString(36);
	var space_icon = '&nbsp;&nbsp;';
	var space_text = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	var html = [
			'<ul id="contextmenu_'+uid+'" data-id="'+mineId+'" data-index="'+mineId+'" data-mold="2">',
			'<li data-type="menuChat"><i class="layui-icon" >&#xe611;</i>'+space_icon+'Send group message</li>',
			'<li data-type="menuProfile"><i class="layui-icon">&#xe60a;</i>'+space_icon+'View group information</li>',
			'<li data-type="menuHistory"><i class="layui-icon" >&#xe60e;</i>'+space_icon+'Message History</li>',
			'<li data-type="menuUpdate">'+space_text+'Modify group icon</li>',
			'<li data-type="menuRemove" data-mold="2">'+space_text+'Disband the group</li>',
			'<li data-type="menuSecede">'+space_text+'Exit the group</li></ul>',
		].join('');
layer.tips(html, othis, {
 	Tips: 1
 	,time: 0
 	,shift: 5
 	,fix: true
 	,skin: 'ayui-box layui-layim-contextmenu'
 	,success: function(layero){
 	 var liCount = (html.split('</li>')).length;
 	var stopmp = function (e) { stope(e); };
 	layero.off('mousedowm',stopmp).on('mousedowm',stopmp);
 	var layerobj = $('#contextmenu_'+uid).parents('.layui-layim-contextmenu');
 	// Move the pop-up box position var top = layerobj.css('top').toLowerCase().replace('px','');
		var left = layerobj.css('left').toLowerCase().replace('px','');
		top = getTipTop(1, top, liCount);
		left = 30 + parseInt(left);
		layerobj.css({'width':'150px', 'left':left+'px', 'top':top+'px'});
		$('.layui-layim-contextmenu li').css({'padding-left':'18px'});
 	}
});

4.4. Right-click menu in the blank area of ​​the group list:

/* Bind right-click event to blank area of ​​group chat */
$('body').on('mousedown', '.layim-list-groups', function(e){
	// Clear all right-click pop-up boxes emptyTips();
 if(3 != e.which) {
 	return;
 }
	// Stop dispatching events e.stopPropagation();

	var othis = $(this);
 if (othis.hasClass('layim-null')) return;
 
	var uid = Date.now().toString(36);
	var space_icon = '&nbsp;&nbsp;';
	var space_text = '&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;';
	var html = [
  			'<ul id="contextmenu_'+uid+'">',
  			'<li data-type="menuResetGroup"><i class="layui-icon" >&#xe669;</i>'+space_icon+'Refresh group chat list</li>',
  			'<li data-type="menuInsertGroup">'+space_text+'Create group chat</li></ul>',
  		].join('');
  
	layer.tips(html, othis, {
		Tips: 1
		,time: 0
		,shift: 5
		,fix: true
		,skin: 'ayui-box layui-layim-contextmenu'
		,success: function(layero){
		 var liCount = (html.split('</li>')).length;
			var stopmp = function (e) { stope(e); };
			layero.off('mousedowm',stopmp).on('mousedowm',stopmp);
			var layerobj = $('#contextmenu_'+uid).parents('.layui-layim-contextmenu');
			var top = e.pageY;
			var left = e.pageX;
			var screenWidth = window.screen.width;
			if(screenWidth-left > 150){
				left = left - 30;
			}else if(screenWidth-left < 110){
				left = left - 180;
			}else{
				left = left - 130;
			}
			if(top > 816){
				top = top - 140;
			}else{
				top = top - 60;
			}
			layerobj.css({'width':'150px', 'left':left+'px', 'top':top+'px'});
			$('.layui-layim-contextmenu li').css({'padding-left':'18px'});
		}
	});
}); 

insert image description here

V. Conclusion

Out of interest, I was quite curious about instant messaging, and then I started to get in touch with layim. At the beginning, I would encounter various small problems every time I made a function. For me, if the problem could not be solved in time, I would not be able to sleep that night. I could only keep looking for information and reading the source code, but I could finally reap the sweet fruits. When implementing the function, I referred to the blog posts of online experts, so if you find similar things, please remind the younger generation!
Due to my limited level, if there are any inappropriate expressions in the article and code, please feel free to correct me.

This concludes this article about the sample code for layim’s right-click menu integration in JavaScript. For more information about layim’s right-click menu integration, please search 123WORDPRESS.COM’s previous articles or continue browsing the following related articles. I hope you will support 123WORDPRESS.COM in the future!

You may also be interested in:
  • JS implementation example of finding whether the attribute value of an object in an array exists
  • JavaScript regular expressions and string search methods
  • Examples of common search, sorting, and deduplication algorithms implemented in JS
  • Detailed explanation of JS binary search algorithm
  • Layim in javascript to find friends and groups

<<:  How to modify the root password of mysql under Linux

>>:  Nginx signal control

Recommend

Mysql cannot select non-aggregate columns

1. Introduction I recently upgraded my blog and a...

Let's talk in depth about the principle and implementation of new in JS

Table of contents definition Constructor bodies a...

How to set up a deployment project under Linux system

1. Modify the firewall settings and open the corr...

Summary of solutions for MySQL not supporting group by

I downloaded and installed the latest version of ...

CentOS6.9+Mysql5.7.18 source code installation detailed tutorial

CentOS6.9+Mysql5.7.18 source code installation, t...

Summary of MySQL's commonly used concatenation statements

Preface: In MySQL, the CONCAT() function is used ...

Summary of Form Design Techniques in Web Design

“Inputs should be divided into logical groups so ...

CSS eight eye-catching HOVER effect sample code

1. Send effect HTML <div id="send-btn&quo...

Let's talk about the issue of passing parameters to React onClick

Background In a list like the one below, clicking...

Modify the jvm encoding problem when Tomcat is running

question: Recently, garbled data appeared when de...

CSS and JS to achieve romantic meteor shower animation

1. Rendering 2. Source code HTML < body > &...

How to use file writing to debug a Linux application

In Linux, everything is a file, so the Android sy...

Two ways to make IE6 display PNG-24 format images normally

Method 1: Please add the following code after <...

Introduction to Common XHTML Tags

<br />For some time, I found that many peopl...