Vue.js Scroll to Elements on the Page
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:
<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. ?
Comment
Preview may take a few seconds to load.
Markdown Basics
Below you will find some common used markdown syntax. For a deeper dive in Markdown check out this Cheat Sheet
Bold & Italic
Italics *asterisks*
Bold **double asterisks**
Code
Inline Code
`backtick`Code Block```
Three back ticks and then enter your code blocks here.
```
Headers
# This is a Heading 1
## This is a Heading 2
### This is a Heading 3
Quotes
> type a greater than sign and start typing your quote.
Links
You can add links by adding text inside of [] and the link inside of (), like so:
Lists
To add a numbered list you can simply start with a number and a ., like so:
1. The first item in my list
For an unordered list, you can add a dash -, like so:
- The start of my list
Images
You can add images by selecting the image icon, which will upload and add an image to the editor, or you can manually add the image by adding an exclamation !, followed by the alt text inside of [], and the image URL inside of (), like so:
Dividers
To add a divider you can add three dashes or three asterisks:
--- or ***

Comments (2)
Moaaz Eldesoky
thanks man❤❤
Md Obydullah
My pleasure, Moaaz Eldesoky. 🙂