16

I am creating a webapp with vueJs and bootstrap. I want to change CSS class of an element after a particular amount of scroll, Is there some vue way of doing it.

I want something like following:

<div :class="{classA: scrollPosition < 100, classB: scrollPosition > 100}">
</div>

One option I found is by using vue-scroll, which seems promising, but not working.

Is there some other native way as well to achive the same?

2
  • jsbin.com/mecekohete/1/edit?html,js,output would something like this work for you ? Commented Dec 12, 2016 at 9:06
  • @BelminBedak This will work if vue does not provide anything out of box, which probably it does not, Please post this as answer. Commented Dec 12, 2016 at 9:09

1 Answer 1

40

You could try to make it like this

const app = new Vue({
  
  el: '#app',
  
  data: {
    scrollPosition: null
  },
  
  methods: {
    updateScroll() {
      this.scrollPosition = window.scrollY
    }
  },
  
  mounted() {
    window.addEventListener('scroll', this.updateScroll);
  }
  
})

You should also consider removing event listener when component is being destroyed, in order to prevent leaks:

destroy() {
  window.removeEventListener('scroll', this.updateScroll)
}
Sign up to request clarification or add additional context in comments.

1 Comment

I believe destroyed () { ... } is valid for Vue 2, but in Vue 3 this has been replaced with unmounted () { ... }

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.