Created
April 21, 2025 13:47
-
-
Save damian-pastorini/1b15b8223fe4e7def5fd0d6dec07d0c4 to your computer and use it in GitHub Desktop.
Drag and drop by GPT
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<div class="grid-container"> | |
<div class="grid-element"></div> | |
<div class="grid-element"></div> | |
<div class="grid-element"></div> | |
<div class="grid-element"></div> | |
<div class="grid-element"></div> | |
</div> | |
<style> | |
.grid-container { | |
display: flex; | |
gap: 12px; | |
flex-wrap: wrap | |
} | |
.grid-element { | |
width: 100px; | |
height: 100px; | |
background: #e0e0e0; | |
border: 1px solid #bdbdbd; | |
border-radius: 4px; | |
cursor: grab; | |
user-select: none; | |
margin: 0 | |
} | |
</style> | |
<script> | |
function enableDrag(el) { | |
let startX, startY, initialMarginX, initialMarginY; | |
function onMouseDown(evt) { | |
evt.preventDefault(); | |
startX = evt.clientX; | |
startY = evt.clientY; | |
initialMarginX = parseInt(el.style.marginLeft) || 0; | |
initialMarginY = parseInt(el.style.marginTop) || 0; | |
el.style.zIndex = 1000; | |
el.style.cursor = 'grabbing'; | |
document.addEventListener('mousemove', onMouseMove); | |
document.addEventListener('mouseup', onMouseUp); | |
} | |
function onMouseMove(evt) { | |
const dx = evt.clientX - startX, dy = evt.clientY - startY; | |
el.style.marginLeft = `${initialMarginX + dx}px`; | |
el.style.marginTop = `${initialMarginY + dy}px`; | |
} | |
function onMouseUp() { | |
document.removeEventListener('mousemove', onMouseMove); | |
document.removeEventListener('mouseup', onMouseUp); | |
el.style.cursor = 'grab'; | |
el.style.zIndex = ''; | |
} | |
el.addEventListener('mousedown', onMouseDown); | |
} | |
window.addEventListener('DOMContentLoaded', () => { | |
document.querySelectorAll('.grid-element').forEach(enableDrag); | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment