1

i decided to learn Vue.js on a project and i can't get how i can track window scroll and dynamicly change CSS after some distance similar, like i did it with JQuery:

$(window).scroll(function() {
      if($(window).scrollTop() >= 100) {
        $('header').addClass('fixed');
      } else {
        $('header').removeClass('fixed');
      }
    });

1 Answer 1

2

You can use a Custom Directive and bind it to any component or element in your Vue instance.

So say you have a <div> and name your directive on-scroll you would update your div: <div on-scroll="handleScroll"> where handleScroll is the method in your Vue instance that is going to, well, handle the scroll event.

Directive:

Vue.directive('on-scroll', {
  inserted: function (el, binding) {
    let f = function (evt) {
      if (binding.value(evt, el)) {
        window.removeEventListener('scroll', f)
      }
    }
    window.addEventListener('scroll', f)
  }
})

Vue Instance:

new Vue({
  el: '#el',
  methods: {
    handleScroll: (event, el) => {
       if ( window.scrollY >= 300 ) {
          el.classList.add('fixed');
       } else {
          el.classList.remove('fixed');
       }
    }
  }
});
Sign up to request clarification or add additional context in comments.

Comments

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.