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;
}

1 Answer 1

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);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Thanks! I just had to bind this to the context setTimeout(function() { this.scrollTo(target); }.bind(this), 0); but now it works!
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(). vuejs.org/guide/best-practices.html#Understanding_Async_Updates

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.