Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • HTML Tutorial
  • HTML Exercises
  • HTML Tags
  • HTML Attributes
  • Global Attributes
  • Event Attributes
  • HTML Interview Questions
  • HTML DOM
  • DOM Audio/Video
  • HTML 5
  • HTML Examples
  • Color Picker
  • A to Z Guide
  • HTML Formatter
Open In App
Next Article:
Drag and Drop Sortable List Using HTML CSS & JavaScript
Next article icon

Drag and Drop Sortable List Using HTML CSS & JavaScript

Last Updated : 06 Feb, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

The Drag and Drop Sortable List Project in JavaScript allows users to easily reorder items in a list using drag-and-drop functionality. This interactive tool enhances user experience by enabling smooth, dynamic list organization, ideal for applications like task managers or shopping lists.

What we are going to create

We’ll build an application that allows users to

  • Interact with a sortable list using drag-and-drop functionality.
  • Rearrange list items dynamically with smooth animations.
  • Implement event listeners for dragstart, dragend, and dragover to manage the drag process.
  • Use JavaScript to track the dragged item and position it correctly within the list.
  • Provide visual feedback for valid drop targets during the dragging process.

Project Preview

Screenshot-2025-01-15-101039
Drag and Drop Sortable List using HTML CSS & JavaScript

Drag and Drop Sortable List - HTML and CSS Code

This code creates a drag-and-drop sortable list with a sleek UI using HTML and CSS. It includes a stylish design with smooth hover and drag effects.

HTML
<html> <head>     <style>         body {             font-family: 'Poppins', sans-serif;             padding: 20px;             background: linear-gradient(to right, #6a11cb, #2575fc);             color: #fff;             text-align: center;         }         h2 {             margin-bottom: 20px;             font-size: 1.8em;         }         .sortable-list {             list-style: none;             padding: 0;             width: 350px;             margin: auto;             background: rgba(255, 255, 255, 0.1);             border-radius: 10px;             box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);         }         .sortable-item {             padding: 15px 20px;             margin: 8px 0;             background: rgba(255, 255, 255, 0.8);             border-radius: 5px;             font-size: 1.1em;             color: #333;             font-weight: bold;             cursor: grab;             box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);             transition: background 0.2s, transform 0.2s;         }         .sortable-item:hover {             background: #e8f0ff;             transform: scale(1.03);         }         .dragging {             opacity: 0.7;             transform: rotate(-2deg);         }         .over {             border: 2px dashed #ff8c42;             background: #fff3e0;         }     </style> </head> <body>     <h2>Drag and Drop Sortable List</h2>     <ul class="sortable-list">         <li class="sortable-item" draggable="true">Item 1</li>         <li class="sortable-item" draggable="true">Item 2</li>         <li class="sortable-item" draggable="true">Item 3</li>         <li class="sortable-item" draggable="true">Item 4</li>         <li class="sortable-item" draggable="true">Item 5</li>     </ul> </body> </html> 

In this example

  • A <ul> list (sortable-list) contains multiple <li> items (sortable-item), each marked draggable="true" to enable dragging.
  • The body has a gradient background, while the list and items feature rounded corners, shadows, and hover effects for a smooth look.
  • The .dragging class changes opacity and adds a slight tilt, while .over applies a dashed border and background color change when hovering.

Drag and Drop Sortable List -JavaScript

The JavaScript code enables drag-and-drop functionality by handling dragstart, dragend, and dragover events, allowing the user to reorder list items dynamically based on the mouse's vertical position.

JavaScript
const list = document.querySelector('.sortable-list');   let draggingItem = null;    list.addEventListener('dragstart', (e) => {     draggingItem = e.target;     e.target.classList.add('dragging');   });    list.addEventListener('dragend', (e) => {     e.target.classList.remove('dragging');     document.querySelectorAll('.sortable-item').forEach(item => item.classList.remove('over'));     draggingItem = null;   });    list.addEventListener('dragover', (e) => {     e.preventDefault();     const draggingOverItem = getDragAfterElement(list, e.clientY);      // Remove .over from all items     document.querySelectorAll('.sortable-item').forEach(item => item.classList.remove('over'));      if (draggingOverItem) {       draggingOverItem.classList.add('over'); // Add .over to the hovered item       list.insertBefore(draggingItem, draggingOverItem);     } else {       list.appendChild(draggingItem); // Append to the end if no item below     }   });    function getDragAfterElement(container, y) {     const draggableElements = [...container.querySelectorAll('.sortable-item:not(.dragging)')];      return draggableElements.reduce((closest, child) => {       const box = child.getBoundingClientRect();       const offset = y - box.top - box.height / 2;       if (offset < 0 && offset > closest.offset) {         return { offset: offset, element: child };       } else {         return closest;       }     }, { offset: Number.NEGATIVE_INFINITY }).element;   }  

In this example

  • The draggingItem variable stores the item currently being dragged (like identifying a point being moved).
  • On dragstart, the dragged item is marked with a special class (dragging), visually indicating it’s being moved.
  • On dragend, the dragged item’s special visual class is removed, and the variable draggingItem is reset (like finishing the movement and clearing the selection).
  • On dragover, the script calculates where the mouse is vertically and highlights the item being hovered over, so the dragged item can be positioned correctly.
  • The offset is calculated by subtracting the item's top position and dividing its height to determine if the mouse is closer to the top or bottom of an item, helping to decide if the dragged item should appear above or below the current item being hovered over.

Complete Code

HTML
<html> <head>     <style>         body {             font-family: 'Poppins', sans-serif;             padding: 20px;             background: linear-gradient(to right, #6a11cb, #2575fc);             color: #fff;             text-align: center;         }         h2 {             margin-bottom: 20px;             font-size: 1.8em;         }         .sortable-list {             list-style: none;             padding: 0;             width: 350px;             margin: auto;             background: rgba(255, 255, 255, 0.1);             border-radius: 10px;             box-shadow: 0 8px 15px rgba(0, 0, 0, 0.2);         }         .sortable-item {             padding: 15px 20px;             margin: 8px 0;             background: rgba(255, 255, 255, 0.8);             border-radius: 5px;             font-size: 1.1em;             color: #333;             font-weight: bold;             cursor: grab;             box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);             transition: background 0.2s, transform 0.2s;         }         .sortable-item:hover {             background: #e8f0ff;             transform: scale(1.03);         }         .dragging {             opacity: 0.7;             transform: rotate(-2deg);         }         .over {             border: 2px dashed #ff8c42;             background: #fff3e0;         }     </style> </head> <body>     <h2>Drag and Drop Sortable List</h2>     <ul class="sortable-list">         <li class="sortable-item" draggable="true">Item 1</li>         <li class="sortable-item" draggable="true">Item 2</li>         <li class="sortable-item" draggable="true">Item 3</li>         <li class="sortable-item" draggable="true">Item 4</li>         <li class="sortable-item" draggable="true">Item 5</li>     </ul>     <script>         const list = document.querySelector('.sortable-list');         let draggingItem = null;         list.addEventListener('dragstart', (e) => {             draggingItem = e.target;             e.target.classList.add('dragging');         });         list.addEventListener('dragend', (e) => {             e.target.classList.remove('dragging');             document.querySelectorAll('.sortable-item')                 .forEach(item => item.classList.remove('over'));             draggingItem = null;         });         list.addEventListener('dragover', (e) => {             e.preventDefault();             const draggingOverItem = getDragAfterElement(list, e.clientY);             document.querySelectorAll('.sortable-item').forEach                 (item => item.classList.remove('over'));             if (draggingOverItem) {                 draggingOverItem.classList.add('over');                 list.insertBefore(draggingItem, draggingOverItem);             } else {                 list.appendChild(draggingItem);              }         });         function getDragAfterElement(container, y) {             const draggableElements = [...container.querySelectorAll                 ('.sortable-item:not(.dragging)')];             return draggableElements.reduce((closest, child) => {                 const box = child.getBoundingClientRect();                 const offset = y - box.top - box.height / 2;                 if (offset < 0 && offset > closest.offset) {                     return { offset: offset, element: child };                 } else {                     return closest;                 }             }, { offset: Number.NEGATIVE_INFINITY }).element;         }     </script> </body> </html> 

Next Article
Drag and Drop Sortable List Using HTML CSS & JavaScript

L

lunatic1
Improve
Article Tags :
  • HTML
  • JavaScript-Projects
  • Geeks Premier League 2023

Similar Reads

    Build A Drag & Drop Kanban Board using HTML CSS & JavaScript
    A Kanban board is a project management tool designed to visualize work, limit work in progress, and maximize efficiency. With drag & drop functionality, users can easily move tasks between different stages of completion, providing a visual representation of the workflow. Final OutputApproach:The
    4 min read
    Drag and Drop Sortable List Using ReactJS
    Building a drag and drop sortable list in ReactJS allows users to rearrange items interactively by dragging and dropping. This feature enhances the user experience by providing dynamic way to manage lists or items. In this article, we’ll explore how to implement a drag and drop sortable list in Reac
    4 min read
    Create a Sortable and Filterable Table using JavaScript
    In this article, we will demonstrate how to create a sortable and filtrable table using JavaScript. This custom table will have the functionality of editing or removing individual items along with sorting and filtering items according to different fields. Also, a form is attached so that the user ca
    6 min read
    How to Drag and Drop Images using HTML5 ?
    In this article, we will see how to create a drag and drop functionality using HTML5. Approach: The following approach will be implemented to Drag and Drop Images using HTML5. We have given a rectangle area and an image, the task is to drag the image and drop it into the rectangle.We have to enable
    2 min read
    Sortable Drag and Drop with React and Tailwind CSS
    In this tutorial, we'll learn how to create a sortable drag-and-drop feature in a React application using Vite for quick and efficient development, along with Tailwind CSS for styling. This feature allows users to reorder items in a list by dragging and dropping them, enhancing the user experience o
    3 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences