Creating a Draggable Element Using HTML, CSS, and JavaScript
In modern web development, interactivity is key to engaging users and creating a dynamic user experience. One way to add interactivity is by making elements draggable. In this post, we will explore how to create a draggable element using HTML, CSS, and JavaScript.
output:
HTML Structure
Let's start with the basic HTML structure. We will create a simple div element that we want to make draggable. Here's the code:
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Draggable Element</title> <link rel="stylesheet" href="styles.css"> </head> <body> <div class="draggable" id="draggableElement">Drag me!</div> <script src="script.js"></script> </body> </html>
In this code, we have a div with the class draggable and an ID of draggableElement. This will be the element that we make draggable.
Styling the Draggable Element with CSS
.draggable { position: absolute; cursor: grab; width: 100px; height: 100px; background-color: #007bff; color: #fff; text-align: center; line-height: 100px; border-radius: 8px; user-select: none; } .draggable.dragging { cursor: grabbing; }
In this CSS, we define the .draggable class to style our element. We set its position to absolute so that we can move it freely around the page. The cursor property is set to grab to indicate that the element is draggable. We also define the width, height, background color, text color, text alignment, and line height to center the text vertically and horizontally. The border-radius is added for rounded corners, and user-select: none is used to prevent text selection while dragging. Read More
Adding Interactivity with JavaScript
let draggableElement = document.getElementById('draggableElement'); let offsetX, offsetY; draggableElement.addEventListener('mousedown', startDragging); draggableElement.addEventListener('mouseup', stopDragging); function startDragging(e) { e.preventDefault(); offsetX = e.clientX - draggableElement.getBoundingClientRect().left; offsetY = e.clientY - draggableElement.getBoundingClientRect().top; draggableElement.classList.add('dragging'); document.addEventListener('mousemove', dragElement); } function dragElement(e) { e.preventDefault(); let x = e.clientX - offsetX; let y = e.clientY - offsetY; draggableElement.style.left = x + 'px'; draggableElement.style.top = y + 'px'; } function stopDragging() { draggableElement.classList.remove('dragging'); document.removeEventListener('mousemove', dragElement); }
Start Dragging: The startDragging function is triggered when the user presses the mouse button down on the element. This function:
- Prevents the default behavior of the event using e.preventDefault().
- Calculates the offsets by subtracting the element's top-left corner position from the mouse position.
- Adds the dragging class to change the cursor.
- Adds an event listener for the mousemove event to the document, which will trigger the dragElement function.
Drag Element: The dragElement function is triggered when the mouse moves. This function:
- Prevents the default behavior of the event.
- Calculates the new position of the element based on the mouse position and the offsets.
- Updates the left and top CSS properties of the element to move it to the new position.
Stop Dragging: The stopDragging function is triggered when the user releases the mouse button. This function:
- Removes the dragging class to revert the cursor back to its original state.
- Removes the mousemove event listener from the document to stop the dragging. Read More
conclusion:
By understanding the basics of event listeners and DOM manipulation, we can add interactivity to our web projects, enhancing the user experience.
Read full article- click here
The above is the detailed content of Creating a Draggable Element Using HTML, CSS, and JavaScript. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

It's out! Congrats to the Vue team for getting it done, I know it was a massive effort and a long time coming. All new docs, as well.

With the recent climb of Bitcoin’s price over 20k $USD, and to it recently breaking 30k, I thought it’s worth taking a deep dive back into creating Ethereum

I had someone write in with this very legit question. Lea just blogged about how you can get valid CSS properties themselves from the browser. That's like this.

The other day, I spotted this particularly lovely bit from Corey Ginnivan’s website where a collection of cards stack on top of one another as you scroll.

I'd say "website" fits better than "mobile app" but I like this framing from Max Lynch:

There are a number of these desktop apps where the goal is showing your site at different dimensions all at the same time. So you can, for example, be writing

If we need to show documentation to the user directly in the WordPress editor, what is the best way to do it?

Questions about purple slash areas in Flex layouts When using Flex layouts, you may encounter some confusing phenomena, such as in the developer tools (d...
