Reputation: 33
I've created a fiddle here: http://jsfiddle.net/2hzd555w/1/
var canvas = $("#container");
canvas.on('click', '.element-buttons button', function(e) {
e.preventDefault();
var element = $(this).closest('.element');
var element_order = element.find('input.order');
if ($(this).hasClass("move-element-up")) {
var prev = element.prev('.element');
if (prev.length > 0) {
var prev_order = prev.find('input.order');
prev_order.val(element_order.val());
element_order.val(parseInt(element_order.val()) - 1);
}
} else {
var next = element.next('.element');
if (next.length > 0) {
var next_order = next.find('input.order');
next_order.val(element_order.val());
element_order.val(parseInt(element_order.val()) + 1);
}
}
moveElements();
});
var moveElements = function() {
$('.element').sort(function(a, b) {
return parseInt($(a).find('input.order').val()) - parseInt($(b).find('input.order').val());
}).detach().appendTo(canvas);
}
So after you press a couple of up/down buttons to move the divs around, you'll notice the result section will scroll unexpectedly to the top or to another part of the area.
Now this only happens on Chrome, it works as it should in Firefox.
Any help would be much appreciated, I've been banging my head against the wall for weeks.
Note: You may need to click up and down quite a bit (2 minutes in some cases), make sure your scrolled down in the result window as well.
Upvotes: 3
Views: 234
Reputation: 8206
I agree with Rhumborl, that the .detach() is causing this scrolling anomaly .
Another hacky solution is to keep the focus on the item that you clicked with:
$(this).focus();
to be placed after moveElements();
Upvotes: 0
Reputation: 16609
Clearly the .detach()
is basically emptying the page so the scrollbars aren't needed and you end up at the top of the page.
One hacky way around this is to temporarily fix the height of container
, so that the page height remains the same, then remove it after you have done the detach
/attach
:
var moveElements = function() {
// set height to its calculated height
canvas.height(canvas.height());
$('.element').sort(function(a, b) {
return parseInt($(a).find('input.order').val()) - parseInt($(b).find('input.order').val());
}).detach().appendTo(canvas);
// reset the height to auto
canvas.height('');
}
I'm sure there must be a nicer way around this, or you can actual detach and attach elements during the sort, but that sounds inefficient.
Upvotes: 3