Skip to content

Instantly share code, notes, and snippets.

@Akifcan
Created April 30, 2022 19:49
Show Gist options
  • Save Akifcan/91338bdc354f90b01e13c66b297f4f56 to your computer and use it in GitHub Desktop.
Save Akifcan/91338bdc354f90b01e13c66b297f4f56 to your computer and use it in GitHub Desktop.
draggable
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
<style>
* {
margin: 0;
padding: 0;
box-sizing: border-box;
}
body {
min-height: 100vh;
background-color: #dedede;
display: grid;
place-items: center;
}
.list {
position: relative;
width: 200px;
counter-reset: section;
}
.list-item.over {
transform: scale(1.2);
}
.list-item {
position: absolute;
top: 0;
transition: 500ms;
--box-height: 50px;
width: 100%;
height: var(--box-height);
outline: 1px solid red;
}
.list-item::before {
counter-increment: section;
content: counter(section);
}
</style>
</head>
<body>
<div class="list" role="ul">
<div class="list-item">
item
</div>
<div class="list-item">
item
</div>
<div class="list-item">
item
</div>
<div class="list-item">
item
</div>
<div class="list-item">
item
</div>
<div class="list-item">
item
</div>
<div class="list-item">
item
</div>
<div class="list-item">
item
</div>
<div class="list-item">
item
</div>
</div>
<script>
const list = document.querySelector('.list')
const listItem = document.querySelectorAll('.list-item')
let total = 0
listItem.forEach((item, index) => {
total += item.clientHeight
item.style.top = item.clientHeight * index + 'px'
item.setAttribute('draggable', 'true')
item.setAttribute('queue', index)
item.setAttribute('id', index)
item.addEventListener('dragstart', (e) => {
e.dataTransfer.setData("from", item.style.top)
e.dataTransfer.setData("from-queue", index)
e.dataTransfer.setData("id", index)
})
})
list.style.minHeight = total + 'px'
list.addEventListener('drop', (e) => {
e.preventDefault()
const target = e.target
const to = target.style.top
document.getElementById(e.dataTransfer.getData('id')).style.top = to
document.getElementById(e.dataTransfer.getData('id')).setAttribute('queue', target.getAttribute('queue'))
target.style.top = e.dataTransfer.getData('from')
target.setAttribute('queue', e.dataTransfer.getData('from-queue'))
target.classList.remove('over')
})
list.addEventListener('dragover', (e) => {
e.preventDefault()
e.target.classList.add('over')
})
list.addEventListener('dragleave', (e) => {
e.preventDefault()
e.target.classList.remove('over')
})
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment