I have the following grid:
<html>
<head>
<style>
.grid {
display: grid;
grid-template-columns: 100px 100px 100px 100px 100px;
grid-template-rows: 50px 50px 50px 50px;
grid-gap: 10px;
& > * {
padding: 10px;
border: 1px solid black;
}
& > div:first-child {
border: none;
}
& .column-header {
background-color: lightgray;
}
& .row-header {
background-color: lightgray;
}
}
</style>
</head>
<body>
<div class="grid">
<div></div>
<div class="column-header">Col 1</div>
<div class="column-header">Col 2</div>
<div class="column-header">Col 3</div>
<div class="column-header">Col 4</div>
<div class="row-header">Row 1</div>
<div>Cell 1.1</div>
<div>Cell 2.1</div>
<div>Cell 3.1</div>
<div>Cell 4.1</div>
<div class="row-header">Row 2</div>
<div>Cell 1.2</div>
<div>Cell 2.2</div>
<div>Cell 3.2</div>
<div>Cell 4.2</div>
<div class="row-header">Row 3</div>
<div>Cell 1.3</div>
<div>Cell 2.3</div>
<div>Cell 3.3</div>
<div>Cell 4.3</div>
<div class="row-header">Row 4</div>
<div>Cell 1.4</div>
<div>Cell 2.4</div>
<div>Cell 3.4</div>
<div>Cell 4.4</div>
</div>
</body>
</head>
How to use Javascript drag and drop api to:
- drag any of the "Column headers" cells and rearrange the columns horizontally
- drag any of the "Row headers" cells and rearrange the rows vertically
?
2
Answers
Maybe this could help: Try to set some custom attribute to column and row headers, like
draggable
totrue
The grid structure assumes that each cell is an independent element. Rearranging rows or columns involves swapping content rather than rearranging the DOM structure. This solution is suitable for simple grids. I am not sure how complex your grid is.
Here is the working example which is a good start.
Do you want to rearrange the whole row and columns or just the headers?
Let me know if I can assist you further.
I have put together this example:
First, set the
draggable
attribute totrue
for all headers.Then you need to handle each drag event. See HTMLElement: dragstart event.
Lastly, you need to swap rows/columns.
Here is a working example (of course, you need to adjust hardcoded values or make it dynamic for your application):