[Vuejs]-Change background-color of navbar when scroll event with vuejs

21👍

Add event listener to your window and assign new data to your data model and update it’s value when scroll event is started. see code below

date model

data: {
    scrollPosition: null
},

methods

methods: {
    updateScroll() {
       this.scrollPosition = window.scrollY
    }
}

mounted hook

mounted() {
    window.addEventListener('scroll', this.updateScroll);
}

Now in your case, put this in your navbar

<nav :class="{change_color: scrollPosition > 50}">
      ...
      ...
</nav>

and put css to your change_color class

<style scoped>
   .change_color {
       background-color:red
   }
</style

Leave a comment