Question:
There is a table, a certain "top" of users, which is updated every couple of seconds. How is it possible to make the rows ( <tr>
) smoothly swap places? And is it even possible? Now (maybe important) the table occupies less than 50% of the page, it is located in the drop-down block on the right. Here is the html
<table id='topInvest' border-collapse='1'>
<thead>
<tr>
<th>Место</th><th>Игрок</th><th>Очки</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>USERNAME</td>
<td>10</td>
</tr>
<tr>
<td>2</td>
<td>dd301d31</td>
<td>7</td>
</tr>
<tr>
<td>3</td>
<td>Czcz33</td>
<td>5</td>
</tr>
<tr>
<td>4</td>
<td>Username1</td>
<td>2</td>
</tr>
<tr>
<td>5</td>
<td>ff404</td>
<td>2</td>
</tr>
</tbody></table>
If important, the effect of table "scrolling" is implemented in css using this css code
table {display: block; width: 100%; border-collapse: collapse; border-spacing: 0;}
thead, tbody, tr, td, th { display: block; }
thead, tbody{
width: 100%;
}
thead th {
position: sticky;
}
tbody {
height: 40vh;
overflow-y: auto;
}
thead {
width: 100%;
}
tr{
display: flex;
width: 100%;
justify-content: center;
margin: 1rem 0;
}
th, td{
flex: 33%;
}```
Answer:
Keep an example, but you should not consider it as the only possible one + I did not do any checks for the entered values, etc.
To change the position, change the numbers in the blocks.
function sort(items) {
items.sort((a, b) => (+b.innerText) - (+a.innerText))
}
function setPositions(items) {
items.forEach((item, i) => item.style.setProperty('--pos', i))
}
function getItemHeight(item) {
return item.getBoundingClientRect().height
}
function setParentHeight(parent, itemHeight, n) {
parent.style.setProperty('--height', itemHeight * n + 'px')
}
function update(items) {
sort(items)
setPositions(items)
}
let items = [...document.querySelectorAll('.item')]
items.forEach(item => item.addEventListener('input', () => update(items)))
setParentHeight(
document.querySelector('.table'),
getItemHeight(items[0]),
items.length
)
update(items)
body {
height: 100vh;
margin: 0;
display: flex;
align-items: center;
justify-content: center;
overflow: hidden;
}
.table {
position: relative;
width: 200px;
height: var(--height);
}
.item {
position: absolute;
top: 0;
left: 0;
width: 100%;
padding: 20px 0;
background-color: lightblue;
outline: none;
text-align: center;
transform: translateY(calc(var(--pos) * 100%));
transition: 0.5s cubic-bezier(.95, -0.54, .52, .75);
}
<div class="table">
<div class="item" contenteditable>1</div>
<div class="item" contenteditable>1</div>
<div class="item" contenteditable>1</div>
</div>