Nourhan Ahmed
Nourhan Ahmed

Reputation: 179

change background-color of navbar when scroll event with vuejs

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>

Upvotes: 0

Views: 10449

Answers (1)

Qonvex620
Qonvex620

Reputation: 3972

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

Upvotes: 22

Related Questions