DEV Community

sium_hossain
sium_hossain

Posted on

6 1

How to detect scroll up and scroll down in Nuxt/Vue

Meantime in working hour I have to make something like this. If i scroll up little bit, I have to make visible my full navbar otherwise small bar is enough to show.
Example How to detect scroll up and scroll down in Nuxt/Vue
That's the reason I have to define a function where this function is responsible find out scroll up and down event. And I done it by this -

At first in created hook we have to add a event listener by -



created() {
        if(process.client){
             window.addEventListener("scroll", this.handleScroll);
        }

  },


Enter fullscreen mode Exit fullscreen mode

and then inside methods and in handleScroll function we will declare a variable which contain current scroll position and make compare with next scroll position



handleScroll() {

    if(process.client){
      var currentScrollPosition = window.scrollY

      if(currentScrollPosition < this.scrollPosition){
         console.log("Scrolling up");
         this.showFullNav = true
         //your desire logic 
      }
      else{
          this.showFullNav = false
          console.log("Scrolling down");
         //your desire logic 

      }

      this.scrollPosition = window.scrollY
    }
}, 


Enter fullscreen mode Exit fullscreen mode

And finally we have to destroy this event when page leave by -



  destroyed() {
    if(process.client){
       window.removeEventListener("scroll",this.handleScroll);  
    }

  },


Enter fullscreen mode Exit fullscreen mode

That's it...

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

Top comments (3)

Collapse
 
kissu profile image
Konstantin BIFERT

You can even use mounted() hook, that way no need to double check if it's on the client.
And AFAIK destroyed(), is only called on the client-side even if it's not listed here: nuxtjs.org/docs/concepts/nuxt-life...

Collapse
 
siumhossain profile image
sium_hossain

Got it
Thank you for sharing your thought 🤜🤛

Collapse
 
kissu profile image
Konstantin BIFERT

You're welcome! 🤗

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more