david-s
11/8/2019 - 11:50 AM

Sticky nav in Vue JS

// Boolean in your template would look like this - <nav class="navigation__inner" :class="{'navigation__inner--sticky': sticky}">

export default {
  name: 'Navigation',
  data() {
    return {
      sticky: false
    };
  },
  methods: {
    stickyNav() {
      const stickNav = document.getElementById('navigation');
      const stickNavY = stickNav.getBoundingClientRect().y;

      window.addEventListener('scroll', () => {
        const currentPos = document.documentElement.scrollTop || document.body.scrollTop;
        if (currentPos > stickNavY) {
          this.sticky = true;
        } else {
          this.sticky = false;
        }
      });
    }
  },
  mounted() {
    this.stickyNav();
  }
};