Vue.js Scroll to Elements on the Page

Published on March 19, 2020 1 min read

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. 🙂

Author

Hey, I'm Md Obydullah. I build open-source projects and write about Laravel, Linux server, modern JavaScript and more on web development. If you enjoy my content, please consider supporting what I do!

Buy me a coffeeBuy me a coffee Follow

Leave a Reply

Your email address will not be published. Required fields are marked *