Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue method scroll div to top

I am learning vue. I have the following method where I add a chat message to a div with id="toolbar-chat". This div allows scrolling on y axis and I would like the div to jump to the top every time a new message is added. Why is my JS not working?

    document.getElementById("toolbar-chat").scrollTop = 0;

My vue method:

    methods: {
        addMessage(message) {
            this.messages.unshift(message);

            document.getElementById("toolbar-chat").scrollTop = 0;

            axios.post(chat_send_route, message)
            .then(response => {
                console.log(response.data);
            });

        }
    }
like image 558
TheRealPapa Avatar asked Aug 13 '17 07:08

TheRealPapa


2 Answers

This is happening due to way vue updates the dom asynchronously. See Reacivity in depth(Async update Queue)

  • To reflect changes immediately use vm.$nextTick(callback)

  • instead of querying the dom element using document.getElementById() I recommend add a ref attribute to your toolbar-chat element and reference it in your method using this.$refs. See docs for more on ref attribute

      <div id="toolbar-chat" ref="toolbarChat"></div>
    

So you method should be

methods: {
    addMessage(message) {
        this.messages.unshift(message);
        this.$nextTick(() => {
            this.$refs.toolbarChat.scrollTop = 0;
        });

        axios.post(chat_send_route, message)
        .then(response => {
            console.log(response.data);
        });

    }
}

Here is the working fiddle

like image 124
Vamsi Krishna Avatar answered Nov 13 '22 00:11

Vamsi Krishna


Here is my solution :

One global div in main container

<div id="topDiv"></div>

One global function put in the Vue prototype :

Vue.prototype.$scrollTop = function () {
  var element = document.getElementById("topDiv");
  var top = element.offsetTop;
  window.scrollTo(0, top);
}

The same anchor everywhere :

<a @click="$scrollTop">Go to the top</a>
like image 12
Ognyan Dimitrov Avatar answered Nov 13 '22 02:11

Ognyan Dimitrov