Categories
Vue Answers

How to dynamically change a CSS class after a scroll position with Vue.js?

Spread the love

We can dynamically change a CSS class based on the scroll position using Vue.js by utilizing a combination of data properties, computed properties, and event listeners.

Below is a basic example of how to achieve this:

<template>
  <div :class="{ 'scrolled': isScrolled }">
    <!-- Our content here -->
  </div>
</template>

<script>
export default {
  data() {
    return {
      isScrolled: false
    };
  },
  mounted() {
    window.addEventListener('scroll', this.handleScroll);
  },
  beforeDestroy() {
    window.removeEventListener('scroll', this.handleScroll);
  },
  methods: {
    handleScroll() {
      // Calculate scroll position
      const scrollPosition = window.scrollY || window.pageYOffset;
      
      // Update isScrolled based on scroll position
      this.isScrolled = scrollPosition > 0;
    }
  }
};
</script>

<style>
/* Define our CSS classes */
.scrolled {
  /* Our styles for scrolled state */
}
</style>

In this example we have a div element whose class is bound dynamically using the :class directive.

The class scrolled will be applied when the isScrolled property is true.

We listen for the scroll event on the window object and call the handleScroll method.

Inside the handleScroll method, we calculate the scroll position using window.scrollY or window.pageYOffset.

Based on the scroll position, we update the isScrolled property, which in turn updates the CSS class dynamically.

Adjust the scroll position threshold or add additional logic in the handleScroll method as needed to fit our specific requirements.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *