Creating Drag and Drop Elements with Pure, Vanilla JavaScript featured image

Creating Drag and Drop Elements with Pure, Vanilla JavaScript

JavaScript is one of the most popular programming languages empowered with more than 24 frameworks and around 84 libraries. It is the only programming language intrinsically supported by all browsers. Besides, the language supports dynamic typing and is an excellent fit for rendering and animation. You can leverage JavaScript to add interactive behavior in the front-end, control the backend, create web and mobile applications, and more. The option to add effects to any website and make it customizable makes the language a favorite among developers globally.

In this guide, we will walk you through the steps of creating drag and drop elements using pure Vanilla JavaScript. Additionally, we will advance a step further and build a “Morning Scheduler” app using the HTML Drag and Drop API event handlers.

Prerequisites

To follow along with this tutorial, you must have:

  • Basics of JavaScript.
  • An insight into HTML and CSS will add a great advantage.

Step 1: Create a New Project

Start with creating a container with two child elements. We will use the first child element to drag and the second child element to store the dragged elements.

Note: In this tutorial, we will treat containers as a store to keep all the dragged elements. In simple terms, all the elements dragged from the first child will be dropped to the second child.

Next, use the cd command to change the directory to the drag-and-drop-demo  folder:

Step 2: Initial Set-up

In this tutorial, we will create HTML, CSS, and JavaScript files and connect them. First, name the files name as index.html, styles.css, and scripts.js files respectively.

Next, add the title as “My Morning Planner” in the index.html file:

Next, link CSS, and add JavaScript to HTML:

Now, we will create an initial container and add the element we want to drag and drop. Make sure to set the attribute draggable="true", and add the list of items you want to drag or drop.

Next, add the following lines of code in the <body> tags:

Save and close the index.html file. After that, try opening the index.html file in your browser and you will see a page opening up:

13 2 1

Next, let’s style our index.html  using CSS and make it look presentable.

Step 3: Styling using CSS

Next, add styles on all the elements we’ve included in our index.html file:

Try opening the index.html file in your browser and see the output:

Creating Drag and Drop Elements with Pure, Vanilla JavaScript 1

Though we have completed structuring and added styles, the elements are still static. That means, we cannot move or scroll elements until we add dynamic features to them. In the next step, we’ll welcome JavaScript and dynamic behaviors.

Step 4: Introducing JavaScript

In this step, we will introduce JavaScript and make all the drag elements functional. In the JS file, set the elements we’re going to need. Let’s define draggable and containers to drag and drop elements respectively.

Add the two lines of code in the scripts.js file:

Next, set up all the event listeners. Begin with adding the dragstart element as the first event listener to add the class list. Similarly, add the dragend element as the second event listener to remove the class list.

Attach the following EventListeners in your scripts.js file:

Next, add the dragover EventListener for hovering and moving our elements around. Set the current draggable element using the querySelector and then append the draggable element to the current container:

By default, dropping inside of an element is disabled. Use e.preventDefault to enable it:

Next, create an element to determine the mouse positioning. Start with creating a function getDragAfterElement where it will take two parameters. The first will be a container and the second parameter y will take care of the wide position of the mouse. Now, use the querySelectorAll function to get our draggable elements. Define a draggableElements to all the draggable elements inside the container:

Next, call a reduce function which will loop through the list of draggable elements and also specify the single element after the mouse cursor. Next, return the reduce function by adding the first element as closest and the second as a child. Also, equate the offset and add conditions.

Add the following lines of code in the scripts.js file:

In the last part, we will set conditions and check the AfterElements. Check the AfterElements using if-else conditions, and if it is set to null, append a child at the end of the list using appendChild. Else, add the element draggable and afterElement as parameters in the insertBefore function.

Include this in the scripts.js file:

Now we have the necessary setup done. Open your browser and run index.html in your browser. You will see the page “My Morning Scheduler” with options to drag and drop. The white line in the middle acts as a bridge to differentiate between the tasks already done to the ones that are yet to be done:

Ezgif.com Gif Maker 1 1

Conclusion

Drag and Drop is an excellent option to use in modern-day websites. In this guide, we have used a handful of event handlers to make the tutorial easy for beginners. There are eight event handlers in total and we encourage you to use them as you advance. Once you’re comfortable using the functions and the code used in this tutorial, you can dive more into JavaScript topics like jQuery and start exploring. You can also try building a To-Do app, weekly progress tracker using JavaScript date and time features, and other applications using the concepts you have just learned.

To further learn more on JavaScript and web development topics, check these resources from our blog:

Happy Computing!