Reputation: 51
How do I hide a div when scrolled to the bottom of a page?
<div id="cookieID">
<p class="cookie-policy">{{ cookiePolicy }}</p>
</div>
Upvotes: 1
Views: 458
Reputation: 2230
data() {
return {
hasScrolledBottom: false,
};
},
mounted(){
window.addEventListener('scroll', this.onScroll, true);
},
beforeDestroy() {
window.removeEventListener('scroll', this.onScroll, true);
},
methods: {
onScroll(){
var element = e.target;
if (element.scrollHeight - element.scrollTop === element.clientHeight){
console.log('bottom scrolled');
this.hasScrolledBottom = true;
} else {
console.log('Im not in bottom scrolled');
this.hasScrolledBottom = false;
}
You can use the variable hasScrolledBottom
to hide the div:
<div id="cookieID" v-if="hasScrolledBottom">
<p class="cookie-policy">{{ cookiePolicy }}</p>
</div>
FYI, scrollHeight
have wide support in browsers, from ie 8 to be more precise, while clientHeight
and scrollTop
are both supported by everyone. Even ie 6. This should be cross browser safe.
Upvotes: 0
Reputation: 1805
Try this:
<template>
<div>
<p v-if="!scrolledToBottom" class="cookie-policy">{{ cookiePolicy }}</p>
</div>
</template>
<script>
export default {
data: () => ({
scrolledToBottom: false,
}),
mounted() {
this.scroll()
},
methods: {
scroll() {
window.onscroll = () => {
const bottomOfWindow =
Math.max(
window.pageYOffset,
document.documentElement.scrollTop,
document.body.scrollTop
) +
window.innerHeight ===
document.documentElement.offsetHeight
if (bottomOfWindow) {
this.scrolledToBottom = true
}
}
},
},
}
</script>
Instead of v-if
you may prefer using v-show
depending of your usecase.
Source: Check if a user has scrolled to the bottom in Vue.js
Upvotes: 2