I am encountering a curious error in the creation of my array. I try to save a sort order of fields when the item is dragged, and this goes good for most of the part. If i grab an item, i save the field order in which they are in my fieldlist, which i push into an array.
This goes well for all fields, except always for the first one. If i move the first item 1 spot down, it will in the array be moved to the last position and not to the 2nd position and I cant wrap my head arround it why it does this behavior. If i move an item to the first spot, it will also bork that by keeping it in the same position, if i drag something else, it will in the end move to that position.
This is its start position, the array result equals to Array(6) [ 1, 2, 5, 8, 9, 10 ]
, however, if i drag the articlenumber field down 1 spot, my array is getting borked.
The array becomes now Array(6) [ 2, 5, 8, 10, 9, 1 ]
rather than Array(6) [ 2, 1, 5, 8, 10, 9 ]
Is my logic wrong?
Each draggable item is made up as following in PHP
echo '<div class="panel panel-default draggable" data-fieldid="'.$instance['fieldid'].'">';
<-- not interesting code -->
echo '</div>';
And this is my javascript which is in JQuery
$('body').on('dragstop', '.draggable', function(e) {
var arr = [];
$('.draggable').each(function(){
var $this = $(this);
if (typeof $(this).data('fieldid') != 'undefined') {
arr.push($this.data('fieldid'));
}
})
console.log(arr);
var vars = {
url : domain + '/core/ajax/profile.php',
form: 'fieldorder',
profileid : $(this).attr('data-value'),
order: arr
};
datahandle(vars);
});
Does anybody see where it goes wrong?
== edit ==
a little more debugging gave me more insight, since this actually happens in the end everywhere, its like its not registering everything correct. I thought it did, but all items when moved are down a notch occasionally. I put a timeout on it to see if it was a registering thing in the DOM, but no avail.
Solved it. The earlier added setTimeout()
functionality was actually the key, however my timer was too short to actually have the DOM registering everything correctly. I had it set to half a second, which is appearantly to slow. If I set it to 1 second. It actually goes correct, odd.
$('body').on('dragstop', '.draggable', function(e) {
var arr = [];
setTimeout(function() {
$('.draggable').each(function(){
var $this = $(this);
if (typeof $(this).data('fieldid') != 'undefined') {
arr.push($this.data('fieldid'));
}
})
var vars = {
url : domain + '/core/ajax/profile.php',
form: 'fieldorder',
profileid : $(this).attr('data-value'),
order: arr
};
datahandle(vars);
console.log(arr);
}, 1000);
});