Simple Steps to Create a Draggable HTML Element with JavaScript (Source code)

Faraz

By Faraz -

Learn how to create a draggable HTML element with JavaScript using our beginner-friendly tutorial. Step-by-step instructions with code examples provided.


Simple Steps to Create a Draggable HTML Element with JavaScript.jpg

Table of Contents

  1. Project Introduction
  2. HTML Code
  3. CSS Code
  4. JavaScript Code
  5. Conclusion
  6. Preview

A draggable HTML element is a feature that allows users to move an element on a web page around the screen using their mouse. This can be a useful feature for creating interactive web pages and improving the user experience. In this tutorial, we will guide you through the process of creating a draggable HTML element using JavaScript.

JavaScript is a popular programming language used for web development, and it provides a way to make websites more interactive and dynamic. By adding JavaScript code to an HTML file, you can create more advanced features that go beyond what is possible with HTML and CSS alone.

In this tutorial, we will assume that you have a basic understanding of HTML and CSS, and some knowledge of JavaScript. However, even if you're new to JavaScript, we will provide clear explanations and code examples to help you understand the process.

By the end of this tutorial, you will have created a draggable HTML element that you can use in your own web development projects.

Let's create a draggable HTML element using HTML, CSS, and JavaScript step by step.

Join My Telegram Channel to Download the Projects Source Code: Click Here

Prerequisites:

Before starting this tutorial, you should have a basic understanding of HTML, CSS, and JavaScript. Additionally, you will need a code editor such as Visual Studio Code or Sublime Text to write and save your code.

Source Code

Step 1 (HTML Code):

To get started, we will first need to create a basic HTML file.

After creating the files just paste the following codes into your file. Make sure to save your HTML document with a .html extension, so that it can be properly viewed in a web browser.

The <!DOCTYPE html> tag declares the document type and version, in this case, HTML5.

The <html lang="en"> tag indicates that the document is in English language.

The <head> section contains metadata for the webpage, such as the title of the page, the character encoding used, and the stylesheet for styling the page.

The <title> tag sets the title of the webpage, which appears in the browser tab.

The <meta charset="UTF-8" /> tag sets the character encoding of the document to UTF-8, which is a widely used character encoding for the web.

The <meta name="viewport" content="width=device-width" /> tag sets the viewport width to the width of the device, which is important for mobile devices.

The <link rel="stylesheet" href="styles.css" /> tag links to an external stylesheet file called "styles.css" which contains the CSS styling for the webpage.

The <body> section contains the content of the webpage, which in this case is a <div> element with the id attribute set to "draggable" and the text "Drag me!" inside. This <div> element will be draggable.

The <script> tag links to an external JavaScript file called "script.js" which contains the code to make the <div> element draggable.

This is the basic structure of our draggable div using HTML, and now we can move on to styling it using CSS.

Step 2 (CSS Code):

Once the basic HTML structure of the draggable element is in place, the next step is to add styling to the element using CSS.

Next, we will create our CSS file. In this file, we will use some basic CSS rules to create our div element.

The body selector applies styles to the entire body of the webpage. The height property sets the height to 100% of the viewport height. The display property is set to flex, which allows for easy horizontal and vertical alignment of elements. The justify-content and align-items properties center the content both horizontally and vertically. The background-color property sets the background color of the body to a dark blue-grey color.

The #draggable selector applies styles specifically to the HTML element with the id attribute set to "draggable". The position property is set to absolute, which means the element is positioned relative to its nearest positioned ancestor (in this case, the body) and will not affect the position of any other elements. The width and height properties set the size of the element to 150 pixels by 150 pixels. The display, justify-content, and align-items properties are set the same as for the body selector. The background-color property sets the background color of the element to a light yellow color. The border-radius property rounds the corners of the element by 5 pixels. The font-size and line-height properties set the size and spacing of the text inside the element. The box-shadow property adds a slight shadow around the element. Finally, the cursor property sets the mouse cursor to "move" when hovering over the element, indicating that it can be dragged.

This will give our draggable HTML element an upgraded presentation. Create a CSS file with the name of styles.css and paste the given codes into your CSS file. Remember that you must create a file with the .css extension.

body{
  height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #1f1d2b;
}

#draggable {
  position: absolute;
  width:150px;
  height: 150px;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #ffd791;
  border-radius: 5px;
  font-size: 24px;
  line-height: 1.5;
  box-shadow: 0px 0px 5px 0px rgba(0, 0, 0, 0.5);
  cursor: move;
} 

Step 3 (JavaScript Code):

Finally, we need to create a draggable function in JavaScript.

The first line of code creates a JavaScript variable called draggable and sets it equal to the HTML element with the id attribute set to "draggable". This is the element that will be made draggable.

The next four lines of code create some variables to store the position of the mouse cursor and the position of the draggable element. These variables will be used to calculate the new position of the draggable element as it is dragged.

The mousedown event listener is added to the draggable element. This event listener triggers the mouseDown function when the user presses down on the mouse button while hovering over the draggable element.

The mouseup event listener is added to the window object. This event listener triggers the mouseUp function when the user releases the mouse button, regardless of where the cursor is on the webpage.

The mouseDown function is called when the mousedown event is triggered. This function takes in the event object e and prevents its default behavior. It then calculates the posX and posY variables by subtracting the position of the draggable element from the position of the mouse cursor. Finally, it adds the moveElement function as a mousemove event listener to the window object. This function will be called every time the user moves the mouse cursor while holding down the mouse button.

The mouseUp function is called when the mouseup event is triggered. This function removes the moveElement function as a mousemove event listener from the window object. This means that the moveElement function will no longer be called when the user moves the mouse cursor.

The moveElement function is called every time the user moves the mouse cursor while holding down the mouse button. It takes in the event object e and calculates the new mouseX and mouseY variables by subtracting the posX and posY variables from the position of the mouse cursor. It then sets the left and top CSS properties of the draggable element to the new mouseX and mouseY values, respectively. This effectively moves the draggable element to the new position based on the movement of the mouse cursor.

Create a JavaScript file with the name of script.js and paste the given codes into your JavaScript file and make sure it's linked properly to your HTML document, so that the scripts are executed on the page. Remember, you’ve to create a file with .js extension.

var draggable = document.getElementById('draggable');

var posX = 0,
    posY = 0,
    mouseX = 0,
    mouseY = 0;

draggable.addEventListener('mousedown', mouseDown, false);
window.addEventListener('mouseup', mouseUp, false);

function mouseDown(e) {
  e.preventDefault();
  posX = e.clientX - draggable.offsetLeft;
  posY = e.clientY - draggable.offsetTop;
  window.addEventListener('mousemove', moveElement, false);
}

function mouseUp() {
  window.removeEventListener('mousemove', moveElement, false);
}

function moveElement(e) {
  mouseX = e.clientX - posX;
  mouseY = e.clientY - posY;
  draggable.style.left = mouseX + 'px';
  draggable.style.top = mouseY + 'px';
}

Final Output:

Simple Steps to Create a Draggable HTML Element with JavaScript.gif

Conclusion:

In conclusion, you have successfully created a draggable HTML element using JavaScript. Through this tutorial, we have guided you through the steps of creating an HTML file, adding CSS styling to make it visually appealing, and adding JavaScript code to make the element draggable.

We hope this tutorial has been helpful in improving your web development skills and providing a better understanding of how JavaScript can be used to create more advanced web features.

Creating draggable elements is just one example of the many ways that JavaScript can be used to enhance website functionality and user experience. With practice, you can continue to expand your skills and knowledge of JavaScript to create even more dynamic and interactive web pages.

We encourage you to continue practicing what you've learned and exploring the many other features and capabilities of JavaScript. Thank you for following along with this tutorial, and we wish you all the best in your future web development endeavors!

That’s a wrap!

I hope you enjoyed this post. Now, with these examples, you can create your own amazing page.

Did you like it? Let me know in the comments below 🔥 and you can support me by buying me a coffee

And don’t forget to sign up to our email newsletter so you can get useful content like this sent right to your inbox!

Thanks!
Faraz 😊

End of the article

Subscribe to my Newsletter

Get the latest posts delivered right to your inbox


Latest Post

Please allow ads on our site🥺