Skip to content

Instantly share code, notes, and snippets.

@ismasan
Last active May 28, 2024 16:08
Show Gist options
  • Save ismasan/7d132dab3530641837348de0589f9373 to your computer and use it in GitHub Desktop.
Save ismasan/7d132dab3530641837348de0589f9373 to your computer and use it in GitHub Desktop.
Example for reordering CSS grids layout
<html>
<head>
<title>grid</title>
<style>
body {padding: 0; margin: 0;}
.container {
display: grid;
grid-template-rows: 200px repeat(4, 100px);
grid-template-columns: repeat(4, 1fr);
grid-template-areas: "header header header header"
"sidebar main main main"
"sidebar main main main"
"sidebar main main main"
"footer footer footer footer"
}
.one {
grid-area: header;
background: yellow;
}
.two {
grid-area: sidebar;
background: aqua;
}
.three {
grid-area: main;
background: red;
}
.four {
grid-area: footer;
background: green;
}
.five {
background: pink;
}
.six {
background: brown;
}
.dragging {
border: dashed gray 1px;
}
</style>
</head>
<body>
<div class="container">
<div class="editable one" id="one">
one
</div>
<div class="editable two">Two</div>
<div class="editable three" id="three">Three</div>
<div class="editable four">Four</div>
<div class="editable five">Five</div>
<div class="editable six">Six</div>
</div>
<script>
function dragStart(ev) {
ev.target.classList.add('dragging')
ev.dataTransfer.setData("text/plain", ev.target.id);
ev.dataTransfer.dropEffect = "copy";
}
function drop(ev) {
ev.preventDefault();
var draggableId = ev.dataTransfer.getData("text");
var droppable = ev.currentTarget;
var draggable = document.getElementById(draggableId)
draggable.classList.remove('dragging')
var droppableArea = window.getComputedStyle(droppable).gridArea;
var draggableArea = window.getComputedStyle(draggable).gridArea;
draggable.style.gridArea = droppableArea;
droppable.style.gridArea = draggableArea;
console.log(draggable.id, '====>', droppableArea)
console.log(droppable.id, '====>', draggableArea)
}
function dragover(ev) {
ev.preventDefault();
}
function setup() {
var els = document.getElementsByClassName("editable");
var c = 1;
Array.prototype.forEach.call(els, function (e) {
e.draggable = true
e.ondragstart = dragStart
e.ondrop = drop
e.ondragover = dragover
if(e.id == "") {
e.id = "_editable_" + c;
c++
}
})
}
setup()
</script>
</body>
</html>
@cliffordfajardo
Copy link

Live code sanbox of the implementation above: https://jsbin.com/jexuriquma/1/edit?html,output

Similar example but with ghost placeholder item: https://codepen.io/makhtar/pen/YzPJRpX

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment