DEV Community

loading...

Box shadow on scroll :) - VueJS Scroll Event to get the position of the page.

justaashir profile image Aashir Aamir Khan ・2 min read

Note: If you just want to read about the Navigation Bar and don't want to hear my silly talk, just get to the Harry Potter meme down.

Hey :)
I'm back after a long break, It's a very good experience to talk with all of you again.

Jan 12

I bought up my first domain for my portfolio and blog(I'm not leaving DEV). I was really busy all those days and I just pointed out the domain to my twitter account, I was really seeking out time to design my portfolio but I was a lot busier than ever before, I was working really hard to get things stable in my company(startup). I explored a lot of things, and I have a lot of stories to tell you.

Jan 24

I took a break from my work to fresh up myself and I started designing my website straightforward. I will explain all the things in upcoming posts but this post is just about a problem that I experienced and I have a solution for you all.

MEME

Alt Text

I created a fixed navigation bar like this by applying the position property on the main navigation bar container:

   nav{
     position: fixed;
     top: 0px;
  }
Enter fullscreen mode Exit fullscreen mode

JustAashir

Now I want to get a box-shadow and a border-bottom when someone scrolls the page.

Justaashir

Solution:

  • First Create a CSS class with these styles applied, so we just have to toggle the class.
  .scroll {
    box-shadow: 1px 2px 18px rgba(0, 0, 0, 0.1);
    border-bottom: 2px solid #257942;
  }
Enter fullscreen mode Exit fullscreen mode
  • create a data property to save the scroll postion.
  data(){
      return{
        scrolled: false
      }
    },
Enter fullscreen mode Exit fullscreen mode
  • Then We have to play with event listeners to get the required information, we have to run the function every time, to record the scroll position.:

methods: {
  handleScroll () {
    this.scrolled = window.scrollY > 0;
  }
},
created () {
  window.addEventListener('scroll', this.handleScroll);
},
destroyed () {
  window.removeEventListener('scroll', this.handleScroll);
}
Enter fullscreen mode Exit fullscreen mode
  • We can now apply the dynamic class like this:
  <nav :class="scrolled ? 'scroll' : ''"> </nav>
Enter fullscreen mode Exit fullscreen mode

That's all, It's the easiest way to bind window events to your app and components.

Final Solution:
Alt Text

Thanks, for reading this post. This is my first post after a long time, so I lost my momentum and style but I hope I can grab it again and you'll hear from me again soon!

Bye :)

Discussion (2)

pic
Editor guide
Collapse
farry_siziba profile image
Fa_Rai

Thank you for this article.
Will try this for my fixed navigation bar.

Collapse
justaashir profile image
Aashir Aamir Khan Author

Thanks for reading it, and please help others by providing the details about your solution later.