Vue.js Scroll to Elements on the Page

avatar
Mar 18, 2020 · Article · 2 min, 405 words

In this short tutorial, I’m going to share how to scroll to elements on the page.

Template Part

We can easily do it with Vue @click directive. I’m making scroll to div. This is the template part:

<template>
  <div id="app">
    <button @click="goto('div1')">Div 1</button>
    <button @click="goto('div2')">Div 2</button>
    <button @click="goto('div3')">Div 3</button>
    <br/>

    <div class="div" ref="div1">This is Div 1</div>
    <div class="div" ref="div2">This is Div 2</div>
    <div class="div" ref="div3">This is Div 3</div>
  </div>
</template>

Script Part

In the script tag, write a method call goto() like this:

<script>
export default {
  methods: {
    goto(refName) {
      var element = this.$refs[refName];
      var top = element.offsetTop;

      window.scrollTo(0, top);
    }
  }
};
</script>

Full Code

Let’s add some gap between the divs using CSS:

<style scoped>
.div {
  height: 1000px;
  padding: 20px;
  border: 2px solid yellow;
}
</style>

So, the final code looks like:

App.vue
<template>
  <div id="app">
    <button @click="goto('div1')">Div 1</button>
    <button @click="goto('div2')">Div 2</button>
    <button @click="goto('div3')">Div 3</button>
    <br />

    <div class="div" ref="div1">This is Div 1</div>
    <div class="div" ref="div2">This is Div 2</div>
    <div class="div" ref="div3">This is Div 3</div>
  </div>
</template>

<script>
export default {
  methods: {
    goto(refName) {
      var element = this.$refs[refName];
      var top = element.offsetTop;

      window.scrollTo(0, top);
    }
  }
};
</script>

<style scoped>
.div {
  height: 1000px;
  padding: 20px;
  border: 2px solid yellow;
}
</style>

That’s all. Thank you.

Comments

No comments yet…