Div Scroller
This page Show an Example of a div scoller button.
First Pattern
Demo
Horizontal Scroll
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
Vertical Scroll
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
Dependencies
{
"tailwindcss": "^3.3.2", // for styling
}Code
vue
<script setup lang="ts">
type Direction = "vertical" | "horizontal";
withDefaults(
defineProps<{
direction?: Direction;
element: HTMLDivElement | undefined;
distance?: number;
}>(),
{
direction: "horizontal",
distance: 250,
}
);
function scrollDiv(
element: HTMLDivElement,
distance: number,
direction: Direction
) {
const currentPosition =
direction == "horizontal" ? element.scrollLeft : element.scrollTop;
const scrollTo = currentPosition - distance;
if (direction == "horizontal") {
element?.scrollTo({
left: scrollTo,
behavior: "smooth",
});
} else {
element?.scrollTo({
top: scrollTo,
behavior: "smooth",
});
}
}
</script>
<template>
<div
:class="direction == 'horizontal' ? 'flex-row' : 'flex-col'"
class="flex gap-2.5 w-fit"
>
<button
@click="scrollDiv(element!, distance, direction)"
class="rounded-xl px-5 hover:bg-rose-600 py-1 text-sm font-semibold bg-rose-500"
>
{{ direction == "horizontal" ? "L" : "T" }}</button
><button
@click="scrollDiv(element!, -distance, direction)"
class="rounded-lg px-5 hover:bg-rose-600 py-1 text-sm font-semibold bg-rose-500"
>
{{ direction == "horizontal" ? "R" : "B" }}
</button>
</div>
</template>vue
<script setup lang="ts">
import { ref } from "vue";
import DivScroller1 from "../components/DivScroller/DivScroller1.vue";
const horizontalDiv = ref<HTMLDivElement>();
const verticalDiv = ref<HTMLDivElement>();
</script>
<template>
<div class="mt-5">
<div>
<p>Horizontal Scroll</p>
<DivScroller1 :element="horizontalDiv" :distance="horizontalDiv?.clientWidth" />
<div
ref="horizontalDiv"
class="mt-5 w-full overflow-auto bg-gray-700 p-3 flex items-center gap-x-4 scroll-px-3 snap-x"
>
<div
v-for="n in 30"
:key="n"
class="w-[150px] h-[150px] shrink-0 rounded bg-gray-400 flex items-center justify-center snap-start"
>
{{ n }}
</div>
</div>
</div>
<p class="mt-10">Vertical Scroll</p>
<div class="flex items-center gap-x-3">
<DivScroller1 :element="verticalDiv" :distance="verticalDiv?.clientHeight" direction="vertical" />
<div
ref="verticalDiv"
class="mt-5 w-fit overflow-auto bg-gray-700 h-full max-h-[400px] p-3 flex flex-col items-center gap-y-4 scroll-py-3 snap-y"
>
<div
v-for="n in 15"
:key="n"
class="w-[150px] h-[150px] shrink-0 rounded bg-gray-400 flex items-center justify-center snap-start"
>
{{ n }}
</div>
</div>
</div>
</div>
</template>