0

how can I change background-color of navbar when scrolling event with Vuejs. I tried V-scroll event by using this answer How to change css while scrolling in Vue this is the code but it does not work?

<nav v-scroll="handleScroll">
        <div class="logo">
          <img src="../assets/images/logo.png" alt="logo" />
          <button id="mobBtn" @click="displayList">
            <i class="fas fa-bars"></i>
          </button>
        </div>

        <ul class="navlist" id="mobList">
          <li>
            <a href>Home</a>
          </li>
          <li>
            <a href>About</a>
          </li>
          <li>
            <a href>Blog</a>
          </li>
          <li>
            <a href>Contact</a>
          </li>
        </ul>
      </nav>
<script>
export default {
  name: "Header",
  data: {},
  methods: {
  handleScroll: function (evt, el) {
    alert("Dddd")
      if (window.scrollY > 50) {
        el.setAttribute(
          'style',
          'background-color: red;'
        )
      }
      return window.scrollY > 100
    }
};
</script>
1

1 Answer 1

22

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
Sign up to request clarification or add additional context in comments.

1 Comment

This worked outstandingly for changing the Vuetify (v-app-bar) from one color to another on scroll. Thank you very much!! I did however use a computed property to update the 'color' prop for that component: appBarColor() { return this.scrollPosition > 10 ? 'rgba(255,255,255,1)' : 'rgba(255,255,255,.5)'; } This effectively changes the app bar color from translucent to solid white as the page is scrolled. Super cool!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.