Instead of changing the order of divs by jquery only, I just want to "change the flex order number" of every div, after selecting a sort method, with jquery.
For example, my select box:
<div id="sorting">
<select>
<option value=".best">Best</option>
<option value=".worst">Worst</option>
</select>
</div>
My list structure:
<div id="wrapper">
<div class="item">
<div class="score">12</div>
</div>
<div class="item">
<div class="score">7</div>
</div>
<div class="item">
<div class="score">42</div>
</div>
<!-- and so on -->
</div>
The css for the list:
#wrapper {
display: flex;
flex-wrap: wrap;
width: 100%;
}
#wrapper > .item {
order: 0;
flex: 0 0 100%;
padding: 20px;
box-sizing: border-box;
background-color: #ccc;
margin: 10px 0;
}
What I want:
On selecting ".best"
, the div with the highest score should get the lowest "flex order number" and so on (for each div). On selecting ".worst"
, the div with the lowest score should get the lowest "flex order number" aso.
My current "jquery only" way:
var best = $('#wrapper > .item').sort(function(b, a) {
var a1 = $(a).find('.score').text(), b1 = $(b).find('.score').text();
return a1.localeCompare(b1, false, {numeric: true})
});
The problem is, that I have to reinitialize all scripts for the ".item"
divs after changing the order. That’s something I want to prevent by the changing just the "flex order number".
3
Answers
It sounds like you want to dynamically change the flex order of the .item divs based on the selected option in the box using jQuery. You can achieve this by modifying the order property of each .item based on their score values. Here’s how you can do it:
I’ve added a step to empty the #wrapper container and then re-append the sorted items. This effectively reorders the items based on the updated sorting order without affecting any additional scripts associated with them. Please give this code a try, and if you encounter any issues, let me know the specifics, and I’ll be glad to assist further.
working example
You can achieve the this by changing the flex order of each
.item
element based on the selected sorting option using jQuery.Try below Code
You don’t need JQuery to implement this. Modern browsers can handle what you’re using JQuery for (at least in this case anyway).
Solution
I wouldn’t try to solve it in one step (it would make maintenance a PITA later).
This way your DOM structure won’t change, just the style property of each element.
Don’t specify a flexbox order out of the box. Let the script handle that.
I used ES 6 syntax (I’m more used to it, and it’s way easier to work with).