Currently, I am working on scroll to top button features.
The button showed up when it is scrollable to bottom. I want to remember the last position when the scroll to top button is clicked. So when the user click the scroll to bottom button , it will return to the last position.
Is there any better idea to retrieve the current scroll position?
ScrollToTopBottom.vue
<template>
<div v-scroll="onScroll">
<v-btn v-if = "!isVisible"
fab fixed bottom right color="primary" @click="toBottom">
<v-icon>mdi-arrow-down-bold-box-outline</v-icon>
</v-btn>
<v-btn v-else
fab fixed bottom right color="primary" @click="toTop">
<v-icon>mdi-arrow-up-bold-box-outline</v-icon>
</v-btn>
</div>
</template>
<script>
export default{
data () {
return {
isVisible: false
}
},
methods: {
onScroll () {
this.isVisible = window.scrollY > 500
},
toTop () {
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
}
)
},
toBottom(){
var scrollPos = window.scrollY || window.scrollTop
window.scrollTo({
top: document.body.scrollHeight,
behavior: 'smooth'
})
}
}
}
</script>
CodePudding user response:
You can save your position on top button click, then check it on bottom click:
Vue.component('scrollToTopButton', {
template: `
<div v-scroll="onScroll">
<v-btn v-if="!isVisible" fab fixed bottom right color="primary" @click="toBottom">
<v-icon>mdi-arrow-down-bold-box-outline</v-icon>
</v-btn>
<v-btn v-else fab fixed bottom right color="primary" @click="toTop">
<v-icon>mdi-arrow-up-bold-box-outline</v-icon>
</v-btn>
</div>
`,
data () {
return {
isVisible: false,
position: 0
}
},
methods: {
onScroll() {
this.isVisible = window.scrollY > 50
},
toTop() {
this.position = window.scrollY
window.scrollTo({
top: 0,
left: 0,
behavior: 'smooth'
})
},
toBottom(){
let pos = this.position > 0 ? this.position : document.body.scrollHeight
window.scrollTo({
top: pos,
behavior: 'smooth'
})
}
}
})
new Vue({
el: "#demo",
vuetify: new Vuetify(),
})
<link href="https://cdn.jsdelivr.net/npm/@mdi/[email protected]/css/materialdesignicons.min.css" rel="stylesheet">
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vue.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/vuetify.js"></script>
<div id="demo" >
<v-app>
<v-main>
<v-container>
<div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>a</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div><div>xxx</div>
<scroll-to-top-button />
</v-container>
</v-main>
</v-app>
</div>