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
I created a fixed navigation bar like this by applying the position property on the main navigation bar container:
nav{
position: fixed;
top: 0px;
}
Now I want to get a box-shadow and a border-bottom when someone scrolls the page.
Solution:
- First Create a CSS class with these styles applied, so we just have to toggle the class. ```css
.scroll {
box-shadow: 1px 2px 18px rgba(0, 0, 0, 0.1);
border-bottom: 2px solid #257942;
}
- create a data property to save the scroll postion.
```js
data(){
return{
scrolled: false
}
},
- 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);
}
- We can now apply the dynamic class like this: ```html
That's all, It's the easiest way to bind window events to your app and components.
Final Solution:
![Alt Text](https://thepracticaldev.s3.amazonaws.com/i/r3w4qqr8dovg4xi3bgt2.gif)
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 :)
Top comments (4)
For performance, please use IntersectionObserver instead of
scroll
events. It has good browser support. Here's a good tutorial: Sticky Page Header Shadow on Scroll | Ryan Mulligan.If that does not work for you, at least mark the event listener as passive if you can. That also has good browser support.
Thank you. This really helped.
Thank you for this article.
Will try this for my fixed navigation bar.
Thanks for reading it, and please help others by providing the details about your solution later.