Home Web Front-end CSS Tutorial Creating a Draggable Element Using HTML, CSS, and JavaScript

Creating a Draggable Element Using HTML, CSS, and JavaScript

Aug 06, 2024 pm 03:14 PM

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:

Creating a Draggable Element Using HTML, CSS, and JavaScript

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>

Copy after login

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;
}

Copy after login

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);
}

Copy after login

Start Dragging: The startDragging function is triggered when the user presses the mouse button down on the element. This function:

  1. Prevents the default behavior of the event using e.preventDefault().
  2. Calculates the offsets by subtracting the element's top-left corner position from the mouse position.
  3. Adds the dragging class to change the cursor.
  4. 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:

  1. Prevents the default behavior of the event.
  2. Calculates the new position of the element based on the mouse position and the offsets.
  3. 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:

  1. Removes the dragging class to revert the cursor back to its original state.
  2. 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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

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

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Vue 3 Vue 3 Apr 02, 2025 pm 06:32 PM

It&#039;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.

Building an Ethereum app using Redwood.js and Fauna Building an Ethereum app using Redwood.js and Fauna Mar 28, 2025 am 09:18 AM

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

Can you get valid CSS property values from the browser? Can you get valid CSS property values from the browser? Apr 02, 2025 pm 06:17 PM

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&#039;s like this.

Stacked Cards with Sticky Positioning and a Dash of Sass Stacked Cards with Sticky Positioning and a Dash of Sass Apr 03, 2025 am 10:30 AM

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.

A bit on ci/cd A bit on ci/cd Apr 02, 2025 pm 06:21 PM

I&#039;d say "website" fits better than "mobile app" but I like this framing from Max Lynch:

Comparing Browsers for Responsive Design Comparing Browsers for Responsive Design Apr 02, 2025 pm 06:25 PM

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

Using Markdown and Localization in the WordPress Block Editor Using Markdown and Localization in the WordPress Block Editor Apr 02, 2025 am 04:27 AM

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

Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Why are the purple slashed areas in the Flex layout mistakenly considered 'overflow space'? Apr 05, 2025 pm 05:51 PM

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...

See all articles