Question:
I'm working on a Vue 3 component where I want to add a scroll event listener to change the header's style when the user scrolls down the page. However, the event listener doesn't seem to work, and no console logs appear when I scroll.
Here is a simplified version of my code:
<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue';
const isScrolled = ref(false);
const handleScroll = () => {
if (window.scrollY > 50) {
isScrolled.value = true;
} else {
isScrolled.value = false;
}
console.log('isScrolled', isScrolled.value);
};
onMounted(() => {
console.log('Mounted and adding scroll listener');
window.addEventListener('scroll', handleScroll);
});
onUnmounted(() => {
console.log('Removing scroll listener');
window.removeEventListener('scroll', handleScroll);
});
</script>
Problem:
The scroll event listener is added in onMounted, but it doesn't trigger when I scroll the page. There's no console output, and the isScrolled value doesn't change.
What I've Tried:
Verified that the component mounts correctly (logs appear in the console during mounting). Simplified the event listener to just log to the console, but still no success.
Your code works perfectly fine when the window is scrolled.
If you want help figuring out why it doesn't work in your case, you'll need to provide a minimal reproducible example to allow us testing potential solutions.
My guess is that in your app the scroll happens on an inner element sized to occupy the entire viewport, not on the window object.
For example, if we add
#app {
height: 100vh;
overflow: auto;
}
to the example above, the code no longer works, because the scroll no longer happens on window, but on div#app
.
To find out which element is being scrolled, right-click on the scrollbar and select "Inspect element". When the console opens, it will open with the element selected (and conveniently placed in $0
, so you can easily console it). This functionality is available in Chrome, FF and Safari. Not sure about other browsers.
If the target is <html>
you're scrolling window
.