Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Vue.js: how to react to page scrolling?

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.

like image 905
realtebo Avatar asked Sep 07 '25 00:09

realtebo


1 Answers

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);
}
like image 51
Byscripts Avatar answered Sep 08 '25 22:09

Byscripts