Advertisement
Guest User

Untitled

a guest
Feb 18th, 2020
169
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.11 KB | None | 0 0
  1. <!DOCTYPE html>
  2. <html>
  3. <style>
  4. #mydiv {
  5. position: absolute;
  6. z-index: 9;
  7. background-color: #f1f1f1;
  8. text-align: center;
  9. border: 1px solid #d3d3d3;
  10. }
  11.  
  12. #mydivheader {
  13. padding: 10px;
  14. cursor: move;
  15. z-index: 10;
  16. background-color: #2196F3;
  17. color: #fff;
  18. }
  19. </style>
  20. <body>
  21.  
  22. <h1>Draggable DIV Element</h1>
  23.  
  24. <p>Click and hold the mouse button down while moving the DIV element</p>
  25.  
  26. <div id="mydiv">
  27. <div id="mydivheader">Click here to move</div>
  28.  
  29. <div id="main"></div>
  30. </div>
  31.  
  32. <script>
  33. //Make the DIV element draggagle:
  34. dragElement(document.getElementById("mydiv"));
  35.  
  36. function dragElement(elmnt) {
  37. var pos1 = 0, pos2 = 0, pos3 = 0, pos4 = 0;
  38. if (document.getElementById(elmnt.id + "header")) {
  39. /* if present, the header is where you move the DIV from:*/
  40. document.getElementById(elmnt.id + "header").onmousedown = dragMouseDown;
  41. } else {
  42. /* otherwise, move the DIV from anywhere inside the DIV:*/
  43. elmnt.onmousedown = dragMouseDown;
  44. }
  45.  
  46. function dragMouseDown(e) {
  47. e = e || window.event;
  48. e.preventDefault();
  49. // get the mouse cursor position at startup:
  50. pos3 = e.clientX;
  51. pos4 = e.clientY;
  52. document.onmouseup = closeDragElement;
  53. // call a function whenever the cursor moves:
  54. document.onmousemove = elementDrag;
  55. }
  56.  
  57. function elementDrag(e) {
  58. e = e || window.event;
  59. e.preventDefault();
  60. // calculate the new cursor position:
  61. pos1 = pos3 - e.clientX;
  62. pos2 = pos4 - e.clientY;
  63. pos3 = e.clientX;
  64. pos4 = e.clientY;
  65. // set the element's new position:
  66. elmnt.style.top = (elmnt.offsetTop - pos2) + "px";
  67. elmnt.style.left = (elmnt.offsetLeft - pos1) + "px";
  68. }
  69.  
  70. function closeDragElement() {
  71. /* stop moving when mouse button is released:*/
  72. document.onmouseup = null;
  73. document.onmousemove = null;
  74. }
  75. }
  76.  
  77. var div = document.createElement("div");
  78. div.style.width = "100px";
  79. div.style.height = "100px";
  80. div.style.background = "red";
  81. div.style.color = "white";
  82. div.innerHTML = "Hello";
  83.  
  84. document.getElementById("main").appendChild(div);
  85. </script>
  86.  
  87. </body>
  88. </html>
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement