Issue applying css when scrolled to bottom of page


#1

Hi everybody, I created a fixed position button, when I scroll to the bottom of the page I want to apply a css style to the button, I’m suing a computed property so it’s reactive but the style is not applying, this is because the computed property is not updating and is always false, why is this?

Here is my component:

<template>
<div :class="{ at_bottom : isAtBottom }" class="LAYOUTbutton1_maincontainer" @click="scrollToY()"></div>
</template>
<!--SCRIPTS-->
<script>
export default{
name: 'LAYOUTbutton1',

computed: {
    isAtBottom: function() { 
        return this.atBottom;
    }
},


data() {
    return {
        atBottom: false,
    }
},


mounted () {
    console.log(this.$options.name+' component successfully mounted');

    window.onscroll = function() {
        if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
            alert('at bottom');
            this.atBottom = true;
        }
        else{
            this.atBottom = false;   
        }
    };
},


methods:{

    scrollToY: function(){
        if(this.atBottom){
            window.scrollTo(0,document.body.scrollHeight);    
        }
        window.scrollTo(0,0);
    }
}


}
</script>
<!--STYLES-->
<style scoped>
.at_bottom{background-color:green !important;}
.LAYOUTbutton1_maincontainer{width:60px; height:60px; background-color:red; position:fixed; right:25px; bottom:25px;}
</style>



#2

Likely because the scope within your function block is not that of the instance. Use an arrow function or set a reference outside the block.

window.onscroll = () => { ... }

or

    let vm = this;

    window.onscroll = function() {
        if ((window.innerHeight + Math.ceil(window.pageYOffset)) >= document.body.offsetHeight) {
            alert('at bottom');
            vm.atBottom = true;
        }
        else{
            vm.atBottom = false;   
        }
    };

Additionally, it’s recommended to use addEventListener, mainly so you can add events without overwriting any other events currently on the same element (though I’d never suggest to have multiple scroll events, even one can be resource quite heavy).