project demo
html code
Draggable Card
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';
});