Skip to content

Commit 356387f

Browse files
committed
feat(useScrollTop): enhance scroll visibility logic with showOnScrollUp support
1 parent 489a885 commit 356387f

1 file changed

Lines changed: 23 additions & 7 deletions

File tree

src/composables/useScrollTop.js

Lines changed: 23 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,4 @@
1-
import { ref, onMounted, onUnmounted, unref } from 'vue';
1+
import { ref, onMounted, onUnmounted, unref, watch } from 'vue';
22

33
export function useScrollTop(threshold = 300, showOnScrollUp = false) {
44
const isVisible = ref(false);
@@ -7,15 +7,23 @@ export function useScrollTop(threshold = 300, showOnScrollUp = false) {
77
const checkScroll = () => {
88
if (typeof window !== 'undefined') {
99
const currentScrollY = window.scrollY;
10+
const thresholdVal = unref(threshold);
11+
const showOnScrollUpVal = unref(showOnScrollUp);
12+
13+
const isPastThreshold = currentScrollY > thresholdVal;
1014
const isScrollingUp = currentScrollY < lastScrollY.value;
11-
const isPastThreshold = currentScrollY > unref(threshold);
12-
13-
if (unref(showOnScrollUp)) {
14-
isVisible.value = isPastThreshold && isScrollingUp;
15+
const isScrollingDown = currentScrollY > lastScrollY.value;
16+
17+
if (showOnScrollUpVal) {
18+
if (isScrollingUp && isPastThreshold) {
19+
isVisible.value = true;
20+
} else if (isScrollingDown || !isPastThreshold) {
21+
isVisible.value = false;
22+
}
1523
} else {
1624
isVisible.value = isPastThreshold;
1725
}
18-
26+
1927
lastScrollY.value = currentScrollY;
2028
}
2129
};
@@ -26,12 +34,16 @@ export function useScrollTop(threshold = 300, showOnScrollUp = false) {
2634
top: 0,
2735
behavior: 'smooth'
2836
});
37+
if (unref(showOnScrollUp)) {
38+
isVisible.value = false;
39+
}
2940
}
3041
};
3142

3243
onMounted(() => {
3344
if (typeof window !== 'undefined') {
34-
window.addEventListener('scroll', checkScroll);
45+
lastScrollY.value = window.scrollY;
46+
window.addEventListener('scroll', checkScroll, { passive: true });
3547
checkScroll();
3648
}
3749
});
@@ -42,6 +54,10 @@ export function useScrollTop(threshold = 300, showOnScrollUp = false) {
4254
}
4355
});
4456

57+
watch([() => unref(threshold), () => unref(showOnScrollUp)], () => {
58+
checkScroll();
59+
}, { immediate: true });
60+
4561
return {
4662
isVisible,
4763
scrollToTop

0 commit comments

Comments
 (0)