Scroll To View Directive
The v-scroll-to
directive is used to scroll to an element when it is clicked. It is also used to scroll to an element when it is dynamically added to the DOM (using v-if
or v-for
).
Usage
vue
<template>
<button v-scroll-to-view="'targetId'">
<span>Scroll to view</span>
</button>
</template>
You scrolled to me
View Code
vue
<script setup></script>
<template>
<main
class="w-full h-56 p-5 rounded-2xl bg-gray-50 dark:bg-zinc-800 overflow-auto"
>
<div class="h-screen flex justify-between flex-col items-center">
<button
v-scroll-to-view="'scroll-to-view'"
class="bg-blue-500 hover:bg-blue-700 text-white font-bold py-2 px-4 rounded"
>
<span>Scroll to view</span>
</button>
<p
id="scroll-to-view"
class="text-2xl font-bold text-center bg-gray-200 dark:bg-zinc-700 rounded-2xl p-5"
>
You scrolled to me
</p>
</div>
</main>
</template>
<style scoped></style>
Arguments
The v-scroll-to
directive does not accept any arguments.
Modifiers
The v-scroll-to
directive does not accept any modifiers.
Source Code
js
export const vScrollToView = {
mounted(el, binding) {
el.addEventListener("click", () => {
handleScroll(binding.value);
});
},
updated(el, binding) {
el.addEventListener("click", () => {
handleScroll(binding.value);
});
},
};
function handleScroll(id) {
setTimeout(() => {
const targetElm = document.getElementById(id);
targetElm.scrollIntoView({
behavior: "smooth",
block: "center",
inline: "nearest",
});
}, 50); // wait for element if it is not rendered yet
}