Random chrome scrolls in Javascript events

I 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 hit a couple of up / down buttons to move the div, you will notice that the results section will unexpectedly scroll up or down to another part of the area.

Now this only happens in Chrome, it works like it does 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 a little (2 minutes in some cases), make sure you scroll in the results window as well.

+3


source to share


2 answers


Obviously, it .detach()

basically empties the page, so no scrollbars are needed and you end up at the top of the page.

One hacky way is to temporarily set the height container

so that the page height stays the same, then remove it after you've done 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('');
}

      



Updated script

I'm sure this should be better, or you can actually detach and attach the items while sorting, but that sounds inefficient.

+3


source


I agree with Rhumborl that .detach () causes this scrolling anomaly.



Another hacky solution is to keep focus on the item you clicked on: $(this).focus();

to be placed aftermoveElements();

0


source







All Articles