Create a draggable element using Javascript : A beginners guide

chibuike_kingsley_ff74a4c

chibuike kingsley

Posted on August 11, 2024

Create a draggable element using Javascript : A beginners guide

Table of Content

Introduction

We all know that creating an interactive and user-friendly interface is a key in web development, and the draggable element plays a significant role in achieving this superb user experience. On a personal note whenever i use this feature whether it is on a webpage like drag and drop to upload a file, or drag folders into another folder locally, apart from the smooth user experience, it is faster than going through some long process of manual copying and pasting. Now it is even more rampant and could be seen everywhere. So creating a draggable element is a must skill for any developer.

In this guide i will walk you on how to create a draggable element using just html,css and javascript. We will start from the basics, then we look at some basic concept regarding drag and drop, then we explore the codes that bring this functionality alive. By the end of this guide you will be able to make a draggable element on a webpage. As we have below.

Image showing element being dragged around the webpage
This is the outcome of our project.

Prerequisites

Basic Knowledge

  • Understanding of HTML and CSS.
  • Basic familiarity with JavaScript. Tools
  • Text editor e.g vscode.
  • A Browser such as (e.g chrome,firefox).

Setting up the HTML structure

Before we proceed, we first need to set up the basic HTML structure and apply some styles using CSS. On this structure we will be implementing the drag-and-drop functionality with JavaScript.

  • Step 1: Creating the HTML Page.

We Start by setting up a simple HTML page.

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Draggable</title>
    <link rel="stylesheet" href="drag.css">
</head>
<body>
    <div id="mydiv">
        <div id="mydivheader">
            Click here to move
        </div>
        <p>Move</p>
        <p>this</p>
        <p>DIV</p>

    </div>

    <script src="drag.js"></script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Image shows how create a draggable element outlook without styling
This should be the result of our project at this stage.

-Step 2: Adding the Css styles

Now, we add some styling to make the div elements visually distincts. This will aid the visualization effect when our functionality is in action.

#mydiv{
    position:absolute;
    z-index: 9;
    background-color: gray;
    border: 2px solid black;
    text-align: center;
    cursor: pointer;
}
#mydivheader{
    padding: 10px;
    cursor: move;
    z-index: 10;
    background-color: blue;
    color:azure;
}
body{
    background: #000;
}
Enter fullscreen mode Exit fullscreen mode

With the html and css set up, this is the look of our project and ready to add the drag functionality.

our css stying

Understanding the Drag-and-Drop API

  • Before we dive into the javascript code to create a draggable element, it is important to understand the concept behind the drag-and-drop api and the key events that make this functionality possible.This provides a powerful way to implement drag-and-drop activities on the web application, making it easy to move element around the page.
  • Drag Start: The drag operation begins when the user presses down on the draggable element, usually with a mousedown event. This is where you capture the initial position of the element.
  • Dragging While the user holds down the mouse button and moves the cursor, the mousemove event is activated. This is where you update the element’s position based on the mouse’s current location.
  • Drag End:
    This drag operation gets deactivated when the user releases the mouse button, activating the ‘mouseup’ event. Now the element stops moving at this point.

  • Relevant Javascript Events.

We will be using these Javascript events throughout the project to implement the drag function.

  • Mousedown: This gets activated when the user presses the mouse button and not release it over an element. Then the drag operation begins.
  • Mousemove: This gets activated when the user presses the mouse button and moves the mouse. We will also use this event to update the position of the element as the mouse moves.
  • Mouseup: After the user has released the mouse button, the drag functionality gets deactivated. Then the element drops at the current position the user the drag functionality get deactivated.

Implementing the Draggable Functionality

Building upon the foundation we have laid in the previous section, we are ready to implement the draggable functionality using javascript. We will break down the javascript code, taking it a step at a time until achieve our goal.

Step 1: Build the dragElement function

function dragElement(elmnt){
    var pos1 =0, pos2 = 0, pos3 = 0, pos4 =0

Enter fullscreen mode Exit fullscreen mode

This function called dragElement will take in only one parameter. Which we will see later below
After the function the function is called, var pos1, pos2, pos3 and pos4 are all assigned or set to as 0. We use var and not const so that later In our code we always reassign pos1,…, pos4 something else. Let’s say pos1 = 2,…, pos4 =6.

  if(document.getElementById(elmnt.id + "header ")){
        document.getElementById(elmnt.id + "header").onmousedown= dragMouseDown

Enter fullscreen mode Exit fullscreen mode

Remember in the html element looks something like this.

An image that explains draggable element.
What this lines of code are saying is “check in our dom (the html) if this element with the id elmnt.id + “header” and in our case yes, then add an eventListener whenever the mouse button is pressed down and not yet released to call the dragMouseDown function ( for non programmer, eventListener simpy means perform certain action when a condition is meant in our case it means activate the dragMouseDown function whenever the mouse button is pressed down and not released.)

        }else {
        elmnt.onmousedown = dragMouseDown
    }

Enter fullscreen mode Exit fullscreen mode

If the upper condition is not met then call the dragMouseDown function when the mouse button is pressed down on the elmnt.

Step 2: Build the dragMouseDown function

    function dragMouseDown (e){
        e =e || window.event
        e.preventDefault()

Enter fullscreen mode Exit fullscreen mode

what this code does is, on that current element either our elmnt.id+’header” or elmnt, all default action should be suspended only on the current element i.e ( elmnt+”header” or elmnt) default actions are action like clicking etc

        pos3 = e.clientX
        pos4 = e.clientY

Enter fullscreen mode Exit fullscreen mode

our pos3 and pos4 which were assigned 0, will be updated to the position of the elmnt on the page

        document.onmousemove = elementDrag
        document.onmouseup =  closeDragElement

    }

Enter fullscreen mode Exit fullscreen mode

In our html, whenever the mouse button is released, call the closeDragElement function.

Step 3: Build the elementDrag function

    function elementDrag(e){
        e = e || window.event
        e.preventDefault()

Enter fullscreen mode Exit fullscreen mode

This code has been explained in our previous section.

        pos1 = pos3 - e.clientX
        pos2 = pos4 - e.clientY

Enter fullscreen mode Exit fullscreen mode

while the element is being dragged around the dom, the position of the element changes as well and the values of these positions. The current position of the element is accessed in (e.clientX and e.clienty).
pos 1 and pos 2 enables us to track the movement of the object from its initial position(pos3 and pos4) to its final position ( e.clientx and e.clienty).

An image that describes and shows how draggable element works

        pos3 = e.clientX
        pos4 = e.clientY

        elmnt.style.top = ( elmnt.offsetTop - pos2) + "px"
        elmnt.style.left = (    elmnt.offsetLeft - pos1) + "px"
    }

Enter fullscreen mode Exit fullscreen mode

This updates the position of the element in the dom which causes the movement.

Step 4: build the closeDragElement function

    function closeDragElement (){
        document.onmousemove = null
        document.onmouseup = null
    }

Enter fullscreen mode Exit fullscreen mode

This function deactivates the function elementDrag that causes the movement.

dragElement(document.getElementById('mydiv'))
Enter fullscreen mode Exit fullscreen mode

Here is our full Javascript code

function dragElement(elmnt){
    var pos1 =0, pos2 = 0, pos3 = 0, pos4 =0
    //we made the element dragable only by the header

    if(document.getElementById(elmnt.id + "header ")){
        document.getElementById(elmnt.id + "header").onmousedown= dragMouseDown

    }else {
        elmnt.onmousedown = dragMouseDown
    }

    function dragMouseDown (e){
        e =e || window.event
        e.preventDefault()

        pos3 = e.clientX
        pos4 = e.clientY

        document.onmousemove = elementDrag
        document.onmouseup =  closeDragElement

    }

    function elementDrag(e){
        e = e || window.event
        e.preventDefault()
        pos1 = pos3 - e.clientX
        pos2 = pos4 - e.clientY

        pos3 = e.clientX
        pos4 = e.clientY

        elmnt.style.top = ( elmnt.offsetTop - pos2) + "px"
        elmnt.style.left = (    elmnt.offsetLeft - pos1) + "px"
    }
    function closeDragElement (){
        document.onmousemove = null
        document.onmouseup = null
    }

}

Enter fullscreen mode Exit fullscreen mode

Testing and debugging

After implementing the draggable functionality, it very important to see what your application will look like across different platform so as to correct and debug whatever issue that may arise. This will guide you on how to correct any error that will hinder our draggability from functioning on multiple platforms.

  • Testing for compatibility across multiple browsers: Test the draggable element in multiple browsers (e.g., Chrome, Firefox, Safari, Edge) to ensure consistent behavior. While modern browsers generally support basic drag-and-drop functionality, subtle differences can exist in how events are handled.
  • Test for Responsiveness: Resize your browser window to different screen sizes and test how the draggable element behaves. Make sure that the element remains draggable on smaller screens and that it doesn't break the layout.

- Common Issues and Troubleshooting

1. Element Jumping or Lagging:
Issue: The draggable element "jumps" when you start dragging it or doesn't follow the cursor smoothly.

  • Solution: Ensure that you're correctly calculating the pos1 and pos 2 position between the mouse position and the element's position during the mousedown event. Also, make sure that the mousemove event is efficiently updating the element's position.
       pos1 = pos3 - e.clientX
       pos2 = pos4 - e.clientY

Enter fullscreen mode Exit fullscreen mode

2. Inconsistent Behavior:
Issue: The draggable element behaves inconsistently, such as not always responding to clicks or dragging sporadically.

  • Solution: Check for conflicting CSS styles or JavaScript that may interfere with the draggable functionality. Make sure that the mousedown, mousemove, and mouseup events are correctly attached and that no other scripts are preventing these events from firing.

Debugging Techniques

1. Using Browser Developer Tools:

  • Inspect Element: Use the "Inspect" tool in your browser’s developer tools to examine the draggable element’s properties, such as its position and dimensions, in real-time.
  • Console Logs: Add console.log statements within your event handlers to track the flow of events and variable values. This can help you pinpoint where things might be going wrong.
console.log('Dragging started at:', pos1, pos2);
Enter fullscreen mode Exit fullscreen mode

2. Testing Edge Cases:

  • Test edge cases, such as dragging the element to the very edges of the container or rapidly clicking and dragging to see how the element responds. This can help you notices issues that might not be immediately apparent during normal use.

3. Crosschecking your CSS:

  • Ensure your CSS is not inadvertently causing issues. For example, check for z-index conflicts that could prevent it from being dragged.

Final Checks
Once you have tested and debugged your draggable element, do a final round of checks.

  1. Make sure that the drag element moves freely within the webpage.
  2. Ensure that the drag functionality is responsive across multiple browsers
  3. Verify that no other functionality on the page is broken or affected by the draggable element. After these steps then your good to go.

Conclusion

Conclusion: In this article we discussed the fundamentals of adding draggable function to an element with minimal html, Css and Javascript. With the knowledge obtained from this article one can add draggability in any element in the dom.

here we call the function above.
Feel free to say whatever you notice in the comment section below

💖 💪 🙅 🚩
chibuike_kingsley_ff74a4c
chibuike kingsley

Posted on August 11, 2024

Join Our Newsletter. No Spam, Only the good stuff.

Sign up to receive the latest update from our blog.

Related