3

I'm trying to add class name dynamically. That class is changing display of navbar when scroll offset greater than 50.

This is jQuery code (jQuery to collapse the navbar on scroll):

  $(window).scroll(function() {
    if ($(".navbar-default").offset().top > 50) {
      $(".navbar-fixed-top").addClass("top-nav-collapse");
    } else {
      $(".navbar-fixed-top").removeClass("top-nav-collapse");
    }
  });

This is what I tried:

<script>
export default {
  data() {
    return {
      isSticky: false,
      stickyClass: "top-nav-collapse",
    };
  },
  methods: {
    handleScroll(e) {
      e.prevent();
      if (window.scrollY > 50) {
        this.isSticky = true;
        console.log("deneme");
      } else {
        this.isSticky = false;
      }
    },
  },
  mounted() {
    this.handleScroll();
  },
};
</script>

How can I convert this code?

1 Answer 1

1

Add the scroll event handler in the mounted() function and change the isSticky variable there.

export default {
  data: () => ({
    isSticky: false,
  }),
  mounted() {
    this.scroll_event_handler = () => {
      this.isSticky = window.scrollY > 50;
    }
    window.addEventListener("scroll", this.scroll_event_handler);
  },
  unmounted() {
    window.removeEventListener("scroll", this.scroll_event_handler);
  },
}

Then in your template you can add/remove the class like this:

<nav class="navbar-fixed-top" :class="{'top-nav-collapse': isSticky}">
    ...
</nav>
Sign up to request clarification or add additional context in comments.

1 Comment

The scroll-handler should be cached, so that it could be removed on unmount to avoid a memory leak.

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.