someone_that_needHelp
someone_that_needHelp

Reputation: 155

Vue2 js scrolling call function

Is there anyway to call a method on vue after the viewer scrolled certain amount of page percentage?

For example, i would like to run a method to display an offer after the viewer has scrolled 80% of the page from top to bottom.

Upvotes: 0

Views: 538

Answers (1)

Momo
Momo

Reputation: 960

<script>
export default {
  mounted() {
    window.addEventListener("scroll", this.handleScroll);
  },
  destroyed() {
    window.removeEventListener("scroll", this.handleScroll);
  },
  methods: {
    handleScroll(event) {
      // Any code to be executed when the window is scrolled
      const offsetTop = window.scrollY || 0;
      const percentage = (offsetTop * 100) / document.body.scrollHeight;

      // Do something with the percentage
    },
  },
};
</script>

Note If you want to do something ( for example task() ) with a condition that the percentage is equal or greater than some value you must considering a data variable container that how many times that condition is true and do the operation just one time after that.

<script>
export default {
  data() {
    return {
      reached: false, // checker container
    };
  },
  methods: {
    task() {
      console.log("Triggered just one time >= 80");
    },
    handleScroll(event) {
      // ... After calculating the percentage ...
      if (percentage >= 80) {
        if (!this.reached) {
          this.task();
          this.reached = true;
        }
      } else this.reached = false;
    },
  },
};
</script>

Live Demo

Upvotes: 3

Related Questions