Creating a Draggable HTML Element using CSS and JavaScript Tutorial

In this tutorial, you can learn how to create a simple Draggable HTML Element using CSS and JavaScript for your dynamic websites or web applications. This tutorial aims to provide students and beginners with a reference for learning some tricks using CSS and JS to develop a creative and interactive UI/UX of a website or web application. Here, I will be providing the scripts of a simple web page that demonstrate the creation of a draggable HTML Element.

What is a Draggable HTML Element?

The Draggable HTML Element is a UI/UX feature of web pages or websites that allows the users to reposition or change the position of an element by dragging it. This kind of feature is commonly implemented in card elements or panels. This feature is useful for users in terms of setting up the element orders or layout according to his/her desire.

How to create a Draggable HTML Element?

A Draggable HTML Element/DIV Element can be achieved easily using CSS and JavaScript. We can design and style the draggable element, wrapper, containers, and target locations. JavaScript will be useful for making dragging and changing the position of the element. Using the JS mousedown, mousemove, and mouseup event listeners to detect and update the element's location and position when dragging. Check out the web page script that I created and provided below to have a better idea of how to create the Draggable HTML Element.

Sample Web Page

The scripts below result in a simple web page that demonstrates the creation of a simple Draggable HTML Element. The web page contains static contents with a single draggable element and 4 targets or possible element locations. The user can simply grab the draggable element and start dragging it into the location they wanted. When dragging, the possible location of the card will be visible.

HTML

Here's the HTML file script named index.html that contains the page layout and content elements.

  1. <!DOCTYPE html>
  2. <html lang="en">
  3. <meta charset="UTF-8">
  4. <meta http-equiv="X-UA-Compatible" content="IE=edge">
  5. <meta name="viewport" content="width=device-width, initial-scale=1.0">
  6. <title>CSS JS - Draggable Element</title>
  7. <link rel="preconnect" href="https://fonts.googleapis.com">
  8. <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
  9. <link rel="stylesheet" href="https://fonts.googleapis.com/css2?family=Material+Symbols+Outlined:opsz,wght,FILL,[email protected],100..700,0..1,-50..200" />
  10. <link rel="stylesheet" href="style.css">
  11. </head>
  12. <div id="wrapper">
  13. <div class="page-title">Draggable HTML Element using HTML, CSS, and JS</div>
  14. <hr style="margin:auto; width:25px">
  15. <!-- Dragble Element Wrapper -->
  16. <div id="draggable-el-wrapper">
  17. <!-- Dragble Element Container -->
  18. <div class="draggable-el-holder">
  19. <!-- Draggable Element -->
  20. <div class="card">
  21. <div class="card-header">Draggable Element</div>
  22. <hr width="30px" style="margin:auto">
  23. <div class="card-body">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Donec ut porta justo, quis tincidunt odio. Mauris efficitur sapien convallis pulvinar sollicitudin.</div>
  24. </div>
  25. <!-- Draggable Element -->
  26. </div>
  27. <!-- Dragble Element Container -->
  28. <!-- Dragble Element Container -->
  29. <div class="draggable-el-holder"></div>
  30. <!-- Dragble Element Container -->
  31. <!-- Dragble Element Container -->
  32. <div class="draggable-el-holder"></div>
  33. <!-- Dragble Element Container -->
  34. <!-- Dragble Element Container -->
  35. <div class="draggable-el-holder"></div>
  36. <!-- Dragble Element Container -->
  37. </div>
  38. <!-- Dragble Element Wrapper -->
  39. </div>
  40. <script src="script.js"></script>
  41. </body>
  42. </html>

Stylesheet

Here is the CSS file script named style.css which is included or loaded on the index page. This file contains the script for the design and styles of the page layout, content, draggable content, and elements layouts when dragging.

  1. @import url('https://fonts.googleapis.com/css2?family=Rubik&display=swap');
  2. @import url('https://fonts.googleapis.com/css2?family=Courgette&family=Secular+One&display=swap" rel="stylesheet');
  3. @import url('https://fonts.googleapis.com/css2?family=Satisfy&display=swap" rel="stylesheet');
  4. :root{
  5. --secular-font: 'Secular One', sans-serif;
  6. --satisfy-font: 'Satisfy', cursive;
  7. }
  8. *{
  9. box-sizing: border-box;
  10. }
  11. body *{
  12. font-family: 'Rubik', sans-serif;
  13. }
  14. /**
  15. Page Design
  16. */
  17. body,
  18. html{
  19. height: 100%;
  20. width: 100%;
  21. margin: 0;
  22. padding: 0;
  23. }
  24. body{
  25. background-color: #363636;
  26. }
  27. /* Page Wrapper */
  28. #wrapper{
  29. width: 100%;
  30. padding: 3em 5em;
  31. }
  32. .page-title{
  33. font-size: 35px;
  34. font-family: var(--secular-font);
  35. letter-spacing: 2px;
  36. text-align: center;
  37. color:#fff;
  38. }
  39.  
  40. /*
  41. Draggable Wrapper and Holder
  42. */
  43. #draggable-el-wrapper{
  44. position:relative;
  45. width: 100%;
  46. margin-top: 1em;
  47. display: flex;
  48. flex-wrap: wrap;
  49. justify-content: space-evenly;
  50. }
  51. #draggable-el-wrapper .draggable-el-holder{
  52. position:relative;
  53. width: 45%;
  54. min-height: 200px;
  55. margin-bottom: 1em;
  56. }
  57. /* Element Holder when Dragging */
  58. #draggable-el-wrapper[data-drag="true"] .draggable-el-holder {
  59. background: #ffffff0a;
  60. }
  61. /* Element Holder hovered when Dragging */
  62. #draggable-el-wrapper[data-drag="true"] .draggable-el-holder[data-dragging-hovered="true"]{
  63. border: 2px dashed #e7e7e7;
  64. background-color: #bbbbbb7d;
  65. }
  66. /* Element Holder current Container when Dragging */
  67. #draggable-el-wrapper[data-drag="true"] .draggable-el-holder:has(.card[data-dragging="true"]){
  68. background: #70b6ff4a;
  69. }
  70.  
  71. /*
  72. Draggable Card
  73. */
  74. .card{
  75. width: calc(100%);
  76. min-height: 200px;
  77. background: #fff;
  78. border:1px solid #dadada;
  79. padding: 2em 1em;
  80. box-shadow: 0px 0px 7px #dadada9c;
  81. cursor: move;
  82. }
  83. .card[data-dragging="true"]{
  84. position: fixed;
  85. z-index: 9;
  86. filter: opacity(.8);
  87. }
  88. .card[data-dragging="true"] > * {
  89. user-select: none;
  90. }
  91. .card .card-header{
  92. font-size: 30px;
  93. font-weight: 400;
  94. text-align: center;
  95. }
  96. .card .card-body{
  97. padding: 1em 0;
  98. text-align: center;
  99. color:#585858;
  100. font-weight:lighter;
  101. }
  102.  

Without the Dragging function script, the provided scripts will output like the following:

Page Layout

Draggable Element using CSS and JS

Page Layout when Dragging

Draggable Element using CSS and JS

JavaScript

Lastly, here's the JS file script named script.js. The script contains the codes for making the dragging feature functional using the JS selectors, methods/functions, APIs, and event listeners. This file is also loaded on the index page.

  1. // Element Wrapper Selector
  2. const DraggableElWrapper = document.getElementById("draggable-el-wrapper");
  3. // Element Holder Selector
  4. const DraggableElHolder = DraggableElWrapper.querySelectorAll('.draggable-el-holder')
  5. // Draggable Element Selector
  6. const DraggableEl = DraggableElWrapper.querySelector('.card')
  7.  
  8. /** Start Drag */
  9. DraggableEl.addEventListener('mousedown', (e) =>{
  10. var _layerLocX = e.layerX
  11. var _layerLocY = e.layerY
  12.  
  13. DraggableEl.style.width = DraggableEl.clientWidth + `px`
  14. DraggableEl.style.Height = DraggableEl.clientHeight + `px`
  15. DraggableElWrapper.dataset.drag='true'
  16. DraggableEl.dataset.dragging='true'
  17.  
  18. // Dragging Event Function
  19. function dragging(e){
  20. console.log('dragging')
  21. var posX = e.clientX
  22. var posY = e.clientY
  23. var possibleTargets = [...DraggableElHolder]
  24. DraggableEl.style.top = (posY - _layerLocY) + 'px'
  25. DraggableEl.style.left = (posX - _layerLocX) + 'px'
  26. possibleTargets.find(el=>{
  27. var rect = el.getBoundingClientRect()
  28. if(posX > rect.x && posX < (rect.x + rect.width) && posY > rect.y && posY < (rect.y + rect.height)){
  29. el.appendChild(DraggableEl)
  30. el.dataset.draggingHovered = true;
  31. }else{
  32. if(!!el.dataset.draggingHovered)
  33. delete el.dataset.draggingHovered
  34. }
  35. })
  36. }
  37. dragging(e);
  38.  
  39. // Trigger Dragging Event
  40. document.addEventListener('mousemove',dragging)
  41. // Stop Dragging Event
  42. document.addEventListener('mouseup', () =>{
  43. DraggableElWrapper.dataset.drag='false'
  44. DraggableEl.dataset.dragging='false'
  45. document.removeEventListener('mousemove', dragging)
  46. DraggableEl.removeAttribute('style')
  47. })
  48. })

Result

The over result of the whole script I have provided above will output something like the following image when the user is dragging the element.

Draggable Element using CSS and JS

DEMO

Draggable Element using CSS and JS

There you go! I have provided also the complete source code zip file of the web page scripts on this site and it is free to download. Feel free to download the file and modify the script to do some more experiments to enhance your programming capabilities. The download button is located below this tutorial's content.

That's the end of this tutorial! I hope this Creating a Draggable HTML Element using CSS and JavaScript Tutorial will help you with what you are looking for and will be useful for your current and future web applications or website projects.

Explore more on this website for more Tutorials and Free Source Codes.

Happy Coding =)

Add new comment