0

I have an html table of data and each item in a row has a list_position field which can be changed and then all of the items will be reordered to match the change on that item.

If I have a long list and I change an item from list_position value from 1 to 1000, I would like the browser to automatically scroll down to that item after the list is re-ordered.

Currently, with this code, I am scrolled to the item's initial position, not its current position.

reorder: function (item, order, e) {

    // reorder stuff ...

    target = $(e.target).closest('tr');

    this.scrollTo(target);
},


scrollTo: function (target) {

    $('html,body').animate({
        scrollTop: target.offset().top - 60
    }, 1000);

    return false;
}
ryanwinchester
  • 11,737
  • 5
  • 27
  • 45

1 Answers1

1

If you just moved the element, its position likely hasn't yet been reflected in the DOM yet. One trick you can use is to wait until the browser's layout has been recalculated by using setTimeout with a timeout of 0.

So instead of this.scrollTo(target);, try using:

setTimeout(function() {
    this.scrollTo(target);
}, 0);

For more information on why this works and when it's useful, please see this Stack Overflow question.


EDIT: Thanks to Bill Criswell for pointing out the Vue.nextTick function, which is a more semantic way to wait for a DOM update (since you're already using the Vue.js library anyway). Using Vue.nextTick, your code would become the following:

Vue.nextTick(function() {
    this.scrollTo(target);
});
Maximillian Laumeister
  • 19,884
  • 8
  • 59
  • 78
  • Thanks! I just had to bind this to the context `setTimeout(function() { this.scrollTo(target); }.bind(this), 0);` but now it works! – ryanwinchester Oct 01 '15 at 03:50
  • Vue has a `nextTick` function that's probably more reliable than this since it waits for Vue to say that all the DOM updates have bee completed (since it's async updated). You would use it like `this.$nextTick();` or `Vue.nextTick(..)` basically instead of the `setTimeout()`. http://vuejs.org/guide/best-practices.html#Understanding_Async_Updates – Bill Criswell Oct 09 '15 at 13:35