Ocelot-Social/webapp/mixins/scrollToAnchor.js
roschaefer 57598df228 refactor: re-use @vbelolapotkov's solution
If we make this a mixin, we can re-use the same solution for e.g. the
comment. If sb. notifies you, the browser automatically scrolls to the
comment in which you have been mentioned.
2019-09-29 14:28:38 +02:00

33 lines
752 B
JavaScript

export function scrollToAnchor(anchor) {
if (!anchor) return
if (!window || !document) {
return
}
const container = document.querySelector(anchor)
if (container) {
const { top } = container.getBoundingClientRect()
setTimeout(() => {
// we have to set a small timeout to ensure this part comes after nuxt
// scrollBehaviour: https://nuxtjs.org/api/configuration-router/#scrollbehavior
window.scroll({
top,
left: 0,
behavior: 'smooth',
})
}, 250)
}
}
export default {
watch: {
$route(to, from) {
const anchor = to && to.hash
scrollToAnchor(anchor)
},
},
mounted() {
const anchor = this.$route && this.$route.hash
scrollToAnchor(anchor)
},
}