Reputation: 25637
I've the need to react to window (viewport) scrolling to be able to detect when an element is visible or not.
The final goal is create something SIMILAR but not equal to an infinite scroller.
I want to learn to make it by myself. Do not link me plugins Please, I need to understand Vue.js before constructing over other's plugins.
How can I detect page (windows, or better the viewport) scrolling and resizing using Vue.js?
OR
How can I overseer the vertical position of an element, a div or a span, to react when it's near to be visibile ?
In the doc I found the @scroll
, but it react to the scrolling of an element, not of the page.
Upvotes: 4
Views: 10748
Reputation: 693
You need to add a listener to the global scroll event on the window
object.
window.addEventListener('scroll', listener)
You can find good advice on how to handle this event properly on MDN: https://developer.mozilla.org/en-US/docs/Web/Events/scroll
You can use Node#getBoundingClientRect
to compute whether your node is visible, this method will provide you with the top position of your node within its scrollable container, you can use the offsetTop property alternatively. To do so you have to retrieve the viewport height, which is window.innerHeight
is your case, and your current scroll position, which is window.scrollY
in your case.
Then you can do something like that:
isVisible = innerHeight - scrollY > offsetTop - scrollY
Upvotes: 2
Reputation: 2588
There is a good suggestion here: https://github.com/vuejs/Discussion/issues/324#issuecomment-240978025
I duplicate the code here for posterity.
data () {
return {
scrolled: false
};
},
methods: {
handleScroll () {
this.scrolled = window.scrollY > 0;
}
},
created () {
window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
window.removeEventListener('scroll', this.handleScroll);
}
Upvotes: 9