Dark CSS

Simple Drag and Drop Card in Html CSS and JavaScript

Facebook
Twitter
WhatsApp

project demo

html code

				
					<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Draggable Card</title>
    <link rel="stylesheet" href="style.css">
</head>

<body>
    <div class="wrapper" id="draggableCard">
        <div class="header">
            <span class="profile"></span>
            <span class="name"></span>
        </div>
        <div class="content"></div>
    </div>
</body>

</html>
				
			

css code

				
					* {
    padding: 0;
    margin: 0;
    box-sizing: border-box;
    font-family: 'consolas', sans-serif;
}

body {
    display: flex;
    justify-content: center;
    align-items: center;
    min-height: 100vh;
    background: #e2d3fe;
}

.wrapper {
    width: 200px;
    display: flex;
    justify-content: center;
    flex-direction: column;
    background: #e5ddf0;
    box-shadow: 4px 10px 10px rgba(0, 0, 0, 0.115);
    border-radius: 17px;
    height: 200px;
    padding: 10px;
    position: absolute;
    /* Changed for draggable functionality */
    cursor: grab;
    /* Changes cursor to indicate draggable */
}

.wrapper:active {
    cursor: grabbing;
    /* Changes cursor when dragging */
}

.wrapper .header {
    width: 100%;
    height: 40px;
    display: flex;
    margin-bottom: 10px;
}

.header .profile {
    background: #cec7f8;
    border-radius: 50%;
    width: 40px;
    height: 40px;
    margin-right: 5px;
}

.header .name {
    background: #cec7f8;
    border-radius: 12px;
    width: 125px;
    height: 40px;
}

.wrapper .content {
    width: 100%;
    height: 100px;
    background: #cec7f8;
    border-radius: 12px;
    margin-top: 10px;
}
				
			

javascript code

				
					const card = document.getElementById('draggableCard');
    let isDragging = false;
    let offsetX, offsetY;

    // Mouse down event - start dragging
    card.addEventListener('mousedown', (e) => {
        isDragging = true;

        // Calculate theoffset between mouse position and card position
        offsetX = e.clientX - card.getBoundingClientRect().left;
        offsetY = e.clientY - card.getBoundingClientRect().top;

        // Change cursor style
        card.style.cursor = 'grabbing';
    });

    // Mouse move event - drag the card
    document.addEventListener('mousemove', (e) => {
       if (!isDragging) return;

        // Calculate new position
        const x = e.clientX - offsetX;
        const y = e.clientY - offsetY;

        // Apply new position
        card.style.left = x + 'px';
        card.style.top = y + 'px';
    });

    // Mouse up event - stop dragging
    document.addEventListener('mouseup', () => {
        isDragging = false;
        card.style.cursor = 'grab';
    });