3๐
โ
<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
๐คMomo
Source:stackexchange.com