Reputation: 3369
I am using SortableJS to implement a ranking system for users.
When I drag and drop an item (for example, moving rank 3 to rank 4), the image that follows the cursor does not update its background color to reflect the new rank.
The floating image (the one following the mouse) keeps the old background color instead of updating to match its new rank.
How to update this floating image's background color dynamically to reflect its new position or, if update is impossible, remove this floating image?
document.addEventListener("DOMContentLoaded", function() {
var sortable = new Sortable(document.getElementById("sortable-list"), {
animation: 150,
ghostClass: "sortable_ghost",
onEnd: function() {
updateRanks();
}
});
function updateRanks() {
document.querySelectorAll("#sortable-list li").forEach((li, index) => {
li.dataset.rank = index + 1;
li.querySelector(".rank").textContent = (index + 1) + ".";
});
}
});
body {
font-family: Arial, sans-serif;
}
ul {
list-style: none;
padding: 0;
max-width: 300px;
margin: 20px auto;
border: 1px solid #ddd;
border-radius: 5px;
padding: 10px;
background: #f9f9f9;
}
li {
background: white;
padding: 10px;
margin: 5px 0;
border: 1px solid #ccc;
cursor: grab;
display: flex;
align-items: center;
}
li:nth-child(1), .r1 {
background-color: rgba(255, 204, 0, 0.75);
box-shadow: 0 2px 8px rgba(255, 204, 0, 0.9);
}
li:nth-child(1)::before, .r1::before {
content: "🥇";
}
li:nth-child(2), .r2 {
background-color: rgba(209, 209, 209, 0.75);
box-shadow: 0 2px 8px rgba(209, 209, 209, 0.9);
}
li:nth-child(2)::before, .r2::before {
content: "🥈";
}
li:nth-child(3), .r3 {
background-color: rgba(205, 127, 50, 0.75);
box-shadow: 0 2px 8px rgba(205, 127, 50, 0.9);
}
li:nth-child(3)::before, .r3::before {
content: "🥉";
}
.rank {
font-weight: bold;
margin-right: 10px;
}
.sortable_ghost {
opacity: 0.5;
background: #e0e0e0;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/Sortable/1.15.0/Sortable.min.js"></script>
<h2 style="text-align: center;">Classement Drag & Drop</h2>
<ul id="sortable-list">
<li data-rank="1"><span class="rank">1.</span> Élément 1</li>
<li data-rank="2"><span class="rank">2.</span> Élément 2</li>
<li data-rank="3"><span class="rank">3.</span> Élément 3</li>
<li data-rank="4"><span class="rank">4.</span> Élément 4</li>
</ul>
Upvotes: 0
Views: 42