Reputation: 125
I am trying to build a jQuery horizontal sortable list with an arrow in between each sortable item div.
I have seen some example where in the sortable change function I can detach the fixed element and then reinsert it.
I am not able to correctly insert the static div at the right position in change function.
CSS:
body {
background: white !important;
}
.my_card_div{
display:flex;
}
.sortable {
list-style-type: none;
margin: 0;
padding: 0;
}
.sortable li {
float: left;
}
.sortable_placeholder {
border: 1px solid #eeeeee;
width: 100px !important;
height: 60px !important;
background: #eeeeee !important;
color: #777620 !important;
border-radius: 10px !important;
margin-right: 10px;
}
.mydiv{
width: 100px !important;
height: 60px !important;
}
.bg-red{
background:red;
}
.bg-yellow{
background: yellow;
}
.bg-gray{
background: gray;
}
HTML:
<div class="my_card_div p-3" id="sortable"
style="border: 2px solid gray;">
<div class="mydiv bg-red">
Test 1
</div>
<div class="mydiv static">
<button type="button" class=" btn bg-tranparent ">
<img alt="next arrow"
src="https://i.dlpng.com/static/png/504728_preview.png"
height="40" width="40">
</button>
</div>
<div class="mydiv bg-yellow">
Test 2
</div>
<div class="mydiv static">
<button type="button" class=" btn bg-tranparent">
<img alt="next arrow"
src="https://i.dlpng.com/static/png/504728_preview.png"
height="40" width="40">
</button>
</div>
<div class="mydiv bg-gray">
Test 3
</div>
</div>
JS:
$("#sortable").sortable({
items: ':not(.static)',
start: function() {
$('.static', this).each(function() {
var $this = $(this);
$this.data('pos', $this.index());
});
},
placeholder: "sortable_placeholder",
change: function(event, ui) {
console.log('change', event, ui);
$sortable = $(this);
console.log($sortable);
$statics = $('.static', this).detach();
$helper = $('<div class="mydiv"></div>').prependTo(this);
$statics.each(function() {
var $this = $(this);
var target = $this.data('pos');
console.log(target)
$this.insertAfter($('.mydiv', $sortable).eq(target));
});
$helper.remove();
},
update: function(event, ui) {
console.log('update', event, ui);
}
});
Upvotes: 1
Views: 324
Reputation: 1984
Add mydiv
class to the sortable placeholder.
Create a list of your static elements and another list of your sortable elements exluding the sortable helper and static elements.
During sortable change, loop through each .mydiv.static
element within the list, detach each static element and then append them after each sortable element for i
.
Here is a fiddle.
$( "#sortable" ).sortable({
items: '.mydiv:not(.static)',
placeholder: "sortable_placeholder mydiv",
change: function(event, ui) {
var statics = $(this).find('.mydiv.static');
var items = $(this).find('.mydiv').not('.static').not('.ui-sortable-helper');
for (var i = 0; i < statics.length; i++) {
var item = items.eq(i);
var static = statics.eq(i).detach();
item.after(static);
}
}
});
Upvotes: 1