Js drags div and when the mouse moves the entire div moves accordingly

  • 2020-03-29 23:56:18
  • OfStack

The HTML code is as follows, where the div to be dragged is the outermost div
<div id="dialog_createUserGroup" class="dialog_main" style=""> 
<div id="McreateUserGroup"> 
<div class="title"> 
<span class="poptitle"> New user group </span> 
<span class="dialog_close" title=" Shut down " onClick="closeUserGroup();"> 
<img src='/images/close.png' alt='close' class='user_img' title=' Shut down '/> 
<!-- New contact --> 
<div class="popContent"> 
<span class="localinfo" style="padding:10px 10px 0 46px;"> Group name </span> 
<input type="text" id="userGroupName" name="userGroupName" class="input_info" value="" style="width:265px;"> 
<img src='/images/ok.png' alt='ok' class='user_img' title='ok' style="display: none;" id="email_ok"/> 
<span id="userGroupName_info" style="margin-left: 100px; color: red;">&nbsp;</span> 
<span class="localinfo" style="padding:10px 10px 0 46px;margin-top:20px"> with &nbsp;&nbsp;&nbsp; households </span> 
<div style="padding-top: 20px;width:265px;display:inline-block"> 
<input type="text" id="group_username" name="group_username" class="input_info" value="" style="width:280px;"> 
<span id="name_info" style="margin-left: 100px; color: red;">&nbsp;</span> 
<span class="localinfo" style="padding:10px 10px 0 46px;"> tracing &nbsp;&nbsp;&nbsp; above </span><br> 
<textarea id="userGroup_displayname" class="textarea_comm" rows="5" name="userGroup_displayname" style="width:265px;margin-left: 100px;"></textarea> 
<a href="javascript:void(0);" id="save_contact_btn" class="dialog_btn2" onclick="saveUserGroup();" style="margin-right: 260px;"> determine </a>    
<a href="javascript:void(0);" class="dialog_btn2" onclick="closeUserGroup();"> cancel </a> 

The js code is as follows,
var flag = true; 
e = e||event; 
var $dialog_createUserGroup = $("#dialog_createUserGroup"); 
var LEFT = e.clientX - parseInt($dialog_createUserGroup.css("left")), 
TOP = e.clientY - parseInt($dialog_createUserGroup.css("top")); 
$(document).mousemove(function (e) { 
e = e || event; 
if (flag) { 
"left": e.clientX - LEFT + "px", 
"top": e.clientY - TOP + "px" 
$(document).mouseup(function (e) { 
flag = false; 

This code shows the dialog box to bind the mouse to listen to the header of the event, when the mouse moves, the entire div also move accordingly!

Related articles: