How to change your navigation style on scroll
Key Takeaways
This video demonstrates how to change the navigation style on scroll using the Intersection Observer API, employing CSS variables and custom properties for easy state switching.
Full Transcript
hello and welcome my name is Kevin and in this video we are going to be looking at how we can use intersection observers to do this thing with the navigation where you know when you scroll down and it shifts from being like transparent to adding a background color to it or something else like that and back off and we're gonna be sort of pushing it a little bit so we're gonna be using intersection observer to do this because it's just more performant than using event listeners on scroll but we're also going to be using CSS variables to make this really easy and fast switch between one state to the other so you don't actually have to like there's almost not much CSS that you have to write when it comes to the change state CSS variables just make that so easy and awesome to do so let's go and see how we can do that okay so here we are in vs coding here we have already set some stuff up and this starting file is linked down below there's one do a github repo that has this starting file so if you want to follow along and there is when to the finished files as well so if you run into any trouble and you want to see the exact code I had you can check out that now what's happening now is we have this page that it looks I think pretty nice here at the top let's just make this a bit bigger so we can see what it would look like so here's sort of where we'd have a logo our main navigation and this other little secondary navigation on the side there and it looks really nice we have a transparent background on it but once we get to here we can't read the text anymore and that sucks and it's nice to have these fixed navigations but that switch when we get to a lower point and intersection observer is really good to be able to do that so what I've done is I've created some classes already so if I come here and I do class is nav scrolled and I save that you're gonna see that we get the white background with the black text and everything like that just really really fast if we come and look at my sass file here oh and really really fast you can see I'm Auto refreshing when I save if you do use my github repo there's a readme there that has really basic instructions on how to use it I'm using gulp to auto refresh and compile my sass so there is a little bit of sass but what I've done is I've created some custom properties here and the reason that custom properties are really really nice for something like this is I'm changing colors in a bunch of places at once but I only have to worry about this and not all the different places that it's actually changing now if you don't know about custom properties I do have a little miniseries there should be a card popping up for that now but in that series and in most tutorials you see on custom properties they are put on the route instead of inside of an actual component like I'm doing here in my header the reason I'm doing that my header is because I'm sort of isolating these colors and these like the text text inverse and background are for this header only and I wouldn't be using them outside of that if it's something where you're using the colors throughout your entire site this doesn't make much sense but since for this really basic demo I'm containing self-contained colors pretty much I've put them in the header and I think that you can use them well in that way and that means anything inside my header does inherit these so that's what I'm actually using on my button when I'm hovering on that it's using it's switching I'm using my text in verse for the text color there and the same thing here on this button so if we go and look I'm using it here so you can see I've set my background color to background in my color to text but if we scroll further down here doot-doot-doot you will find here I have my hover where I'm switching it so my background has become my text color my color is become my text inverse and I'm just making sure that my border matches it so it works properly so my background on my border color stay the same and here on my highlight which is this one here I'm getting I have like sort of the default styling but then I'm going back to those variables for when I hover on top and you're gonna see those are all gonna sort of switch around after so what I've done is when we have that nav scrolled class that comes in I don't have to go through and find my hover here and find my highlight hover and go and find the other thing all I'm doing is switching these things here so I'm just switching those three variables and that means when that class does get put on here let's go put it back on all the colors throughout all that are switching so my hover color gets switched over to black on that it switched over to black on this one my background is switched all of that is happening just by changing this so super super handy and the nice use for custom properties I've just put a little drop shadow on this too to make it stand out a little bit more so the real magic of this one is going to be getting it to switch when we scroll up and down and it's not that hard to do but we just need to add or remove that class but we don't want to do it with a scroll event listener because it just that means the whole time we're scrolling up and down we're just firing off things like crazy whereas we could just listen for one very specific situation to happen and have it switch in that and that's what intersection observer is really really good for now I'm gonna be going a little bit I'm not gonna be spending a lot of time looking at exactly how we're building this out because I've looked at the basics of intersection observer already in another video if you've already watched that you're ready to go if you haven't watched it it might be a good idea to go check it out if you want to try and follow along with this one maybe to be perfect and you'll be able to follow along no problem but if ever I go gloss over something and you're not sure what I was doing or why I did that go and check out the original video the link for it is in the description below and with that you get a better idea of how and why I'm writing all of these things and then just because in this one I'm just focusing on like this specific situation and not on the general happenings or the general behavior of an intersection observer so we're gonna start off by creating a couple of things that we need to keep track of so one of them is my header itself because we need to change the class on that so document query selector and we want to look at my header and the second one that we want to watch for Kant's Const and I'm gonna call it section one and that would be my document query selector and in this case it's I called it home intro and the home intro is this here this dark background that we're looking at so what we want to do is we're gonna be listening like when is this leaving the screen and when it leaves the screen we want to change the background on that and then when it comes back into the screen we want the background to change again on it so we need this is what we're gonna be watching and then this is what we're gonna be changing the class on so with those set up let's come and create our our observer itself so we're gonna do constant now in the original tutorial nasai just did observer I'm gonna call this one section one observer because that's what we're looking at and because once we get through all the different parts of this we're going to have a bunch of different observers going on for this one so we can't just call it observer but it will still be a new intersection observer let's go and make this bigger just for now and I'll shrink it back down after once we start getting some stuff because on our intersection observer we need a few different things one of them is going to be a function so we can say function like that open and close and the second thing we are going to need is the options so we have the two of those coming in now the options I'm also going to change the name of it instead of just being options let's say section one options just so we can keep track of it and so we don't run into any errors I'm going to create that right away section one options is equal to and I'm just going to leave it blank for the moment but we'll come through and actually add some stuff in there a little bit after so here in our function we also need to come in and watch for our entries and I'm also going to put the observer in here even though I'm not sure we're gonna need it in this case because we're not going to on on observe anything but we'll throw it in there as a precaution all right cool so we have a new intersection observer doing a function it's going to be looking at the entries and ad itself and then we're also going to be bringing in these options that are up there and right here we can start our actual function so I'm just gonna hit save on that you can see it reposition things a little bit that's just prettier that's organizing this to try and make it a little bit more readable so here in my function what we're gonna do is we want my entries and for each if you watch the other video you know we're gonna do here each entry now we'll use an arrow function and we can say that let's start off by doing a console log to make sure that this is actually working so entry target because I always like checking along the way instead of running into a problem after like everything else that I've done so we can do our section one observer needs to observe and we want it to observe section one so let's save that so let's shrink this back down because I don't think we need it so big anymore and there we go we can see that it fired off right when the page loaded in there so perfect it is actually working so let's delete this console log because we won't really be needing it since we know it is working um in this case what do we want to do so let's think about this for a second when I scroll down when this leaves the page I want it the the nav class to come in so let's look for one thing at the beginning so we're going to say if entry entry not entries if entry is enter secta and again if you're not sure what why this is going to work please do check out the original video that I did or what the whole is intersecting thing and other stuff along the way so if it is if my entry is intersecting with the page we don't want to have that math class is scrolled on here right so if like say we scroll down and it adds it if we come back up we want to remove it so if entry is an extra let's start off with if the entry isn't intersecting so if it's not intersecting with the page we want to add that class on there right so we can say if it isn't intersecting we can do our header class list add and add nav scrolled to it so if we save that it should when we go down far enough add that there we go so look at that the class just came on and if I go back up well it doesn't leave now though so that's a bit of a problem so let's refresh that again and just watch it one more time so when I scroll down and there we go it clicks on and we see it okay so that's cool so now I'm sure we could write this straight in as just like an else statement so if it isn't intersecting we can do that else we could say that header class list remove nav scroll now this will mean it's going to try so when it is intersecting like right now it'll try and remove it the class isn't there I don't think that's a big of an issue though but if you wanted to you could make this an else--if statement and say like if it is intersecting and if the class list contains nap scroll to remove it but now it should work where when I scroll down it adds it and then when it comes back into the screen it removes it so we can see just like that it's going back and forth and it is working I do have a transition on the background so you can see it's like it sort of transitions in and out it's hard to see you on the white but it is transitioning in and out but the one thing that's a little bit annoying is we have we lose what we're looking at here right at one point this is still intersecting with the screen so it hasn't come in yet so this is where we can use our section option section one options here and I can set the root margin so if I set the root margin it works just like the regular one and I want to work off the top of the page so it can be a percentage or pixel value so we'll stick with pixels so we'll say negative 200 from the top of the page and then we'll just do 0 for the rest of them and you have to put 0 pixels it can't just be 0 and so now you can see it's even though I can see this it's actually white now and once I scroll to a certain point so it's once this is within and I put negative 200 because I'm pushing it downwards by 200 pixels so the way it's working now is it's going down 200 pixels so it's not when it intersects the viewport it's when it intersects 200 pixels away from the top of the viewport so now when I get to there it's switching back and forth so we're sort of preemptively switching it before we can't read the text which just makes it a little bit easier to read and you can see the transition a lot nicer when that switches back and forth now to and of course you can play with that number and everything that you can't use viewport units on that you do have to use pixels or percentages for the root margin that was fun wasn't it I did I had a lot of fun doing that I hope you had fun watching it and I hope you learned a few things on the way as well if you did please let me know in the comments or if you think of other ways you can be able to use this maybe or other ways or approaches you could do please leave a comment down below and let me know I love to have a bit of a discussion about it but if you really want to have an in-depth discussion I'd encourage coming over to the community my community is a free discord channel you can just go down in the description below find the link click on it and you're in there's literally no other steps it's super super easy to do there's a whole bunch of people in there we're having lots of fun and cool discussions and if you have questions or run into problems it's a lot easier to ask there and find out stuff there and just also meet people along the way than it is in the YouTube comments down below so I look forward to seeing you there in the community a big thank you for watching all of us a double big super thank you to my patrons for helping support everything I do here on my channel thank you once again for watching next week we're gonna be looking at another thing you can do with intersection observers so please come and check that one out - it's gonna be those slighty images know when you're scrolling down and things either like fade in or they just appear so if you haven't yet subscribed hit that subscribe button so you you see that video when it comes out because you don't want to miss that it's gonna be pretty cool too but until then of course don't forget to make your corne the internet just a little bit more awesome
Original Description
This video explores using the Intersection Observer API to watch for an element leaving the page and then changing the style of a fixed navigation bar.
GitHub repo: https://github.com/kevin-powell/navbar-change-on-scroll
(includes start and finished versions)
I set up some custom properties ahead of time to make the change really super simple, and then with the use of a little JavaScript to set up our observer, we can add (or remove) a class from our navigation when it reaches the right point on the screen.
#JavaScript #IntersectionObserver #CSS
---
Come and hangout, ask questions, suggest ideas, and meet some awesome people over in The Community: https://discord.gg/nTYCvrK
I have a newsletter! https://www.kevinpowell.co/newsletter
New to Sass, or want to step up your game with it? I've got a course just for you: https://www.kevinpowell.co/learn-sass
---
My Code Editor: VS Code - https://code.visualstudio.com/
How my browser refreshes when I save: https://youtu.be/h24noHYsuGc
---
Support me on Patreon: https://www.patreon.com/kevinpowell
I'm on some other places on the internet too!
If you'd like a behind the scenes and previews of what's coming up on my YouTube channel, make sure to follow me on Instagram and Twitter.
Instagram: https://www.instagram.com/kevinpowell.co/
Twitter: https://twitter.com/KevinJPowell
Codepen: https://codepen.io/kevinpowell/
Github: https://github.com/kevin-powell
Watch on YouTube ↗
(saves to browser)
Sign in to unlock AI tutor explanation · ⚡30
Playlist
Uploads from Kevin Powell · Kevin Powell · 0 of 60
← Previous
Next →
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
How to create an awesome navigation bar with HTML & CSS
Kevin Powell
Improve your CSS by Keepin' it DRY
Kevin Powell
HTML & CSS for Beginners Part 6: Images
Kevin Powell
HTML & CSS for Beginners Part 7: File Structure
Kevin Powell
HTML & CSS for Beginners Part 4: Bold and Italic text and HTML comments
Kevin Powell
HTML & CSS for Beginners Part 5: Links
Kevin Powell
HTML & CSS for Beginners Part 3: Paragraphs and Headings
Kevin Powell
HTML and CSS for Beginners Part 1: Introduction to HTML
Kevin Powell
HTML and CSS for Beginners Part 2: Building your first web page!
Kevin Powell
HTML & CSS for Beginner Part 8: Introduction to CSS
Kevin Powell
HTML & CSS for Beginners Part 9: External CSS
Kevin Powell
HTML & CSS for Beginners Part 10: Divs & Spans
Kevin Powell
HTML & CSS for Beginners Part 11: Classes & IDs
Kevin Powell
HTML & CSS for Beginners Part 12: The CSS Box Model - Margin, Borders & Padding explained
Kevin Powell
HTML & CSS for Beginners Part 13: Background Images
Kevin Powell
HTML & CSS for Beginners Part 14: Style Text with CSS
Kevin Powell
HTML & CSS for Beginners Part 15: How to style links
Kevin Powell
HTML & CSS for Beginners Part 16: CSS selectors and Specificity
Kevin Powell
HTML & CSS for Beginners Part 17: How to Create and Style HTML Lists
Kevin Powell
HTML & CSS for Beginners Part 18: How Floats and Clears work
Kevin Powell
HTML & CSS for Beginners Part 19: Colors with CSS - hex, rgba, and hsla
Kevin Powell
HTML & CSS for Beginners Part 20: How to center a div
Kevin Powell
HTML & CSS for Beginners Part 21: How to create a basic website layout - the HTML
Kevin Powell
HTML & CSS for Beginners Part 22: How to create a basic layout - the CSS
Kevin Powell
How to Create a Responsive Website from Scratch - Part 1: The HTML #Responsive #HTML5
Kevin Powell
How to Create a Responsive Website from Scratch - Part 2: The Header and Hero area #Responsive #CSS3
Kevin Powell
How to Create a Responsive Website from Scratch - Part 3: The About Section #Responsive #CSS
Kevin Powell
How to Create a Responsive Website from Scratch - Part 4: Building a Responsive Portfolio Section
Kevin Powell
How to Create a Responsive Website from Scratch - Part 5: Call To Action and Footer #CSS #Responsive
Kevin Powell
Tutorial: Learn how to use CSS Media Queries in less than 5 minutes
Kevin Powell
End of the year upate and what's coming to my channel to start the new year
Kevin Powell
Create a CSS only Mega Dropdown Menu
Kevin Powell
CSS Tutorial: Outline and Outline Offset
Kevin Powell
CSS Blending Modes
Kevin Powell
Parallax effect | 2 different ways to add it with jQuery
Kevin Powell
CSS Units: vh, vw, vmin, vmax #css #responsive #design
Kevin Powell
How to Create a Website - Complete workflow | Part 01: Intro + Setting things up
Kevin Powell
100 Subscribers speed coding bonus video
Kevin Powell
How to Create a Website - Complete workflow | Part 02: The Markup #HTML
Kevin Powell
How to Create a Website - Complete workflow | Part 03: Sass Variables and a Mixin #Sass
Kevin Powell
How to Create a Website - Complete workflow | Part 04: Setting up the hero and header
Kevin Powell
How to Create a Website - Complete workflow | Part 05: Typography & Buttons
Kevin Powell
How to Create a Website - Complete workflow | Part 06.1: Building the navigation with Flexbox
Kevin Powell
How to Create a Website - Complete workflow | Part 06.2: Making the nav work with jQuery
Kevin Powell
Redesigning & Coding My Website #CreateICG
Kevin Powell
How to Create a Website - Complete workflow | Part 07: Starting the flexbox grid
Kevin Powell
How to Create a Website - Complete workflow | Part 08: Promo & Problem shooting!
Kevin Powell
How to Create a Website - Complete workflow | Part 09: The CTA and Footer
Kevin Powell
How to Create a Website - Complete workflow | Part 10: Making it responsive
Kevin Powell
How to Create a Website - Complete workflow | Part 11: Making it responsive con't
Kevin Powell
How to Create a Website - Complete workflow | Part 12: Putting the site online
Kevin Powell
Create a Custom Grid System with CSS Calc() and Sass
Kevin Powell
CSS em and rem explained #CSS #responsive
Kevin Powell
Should you use Bootstrap?
Kevin Powell
How to add Smooth Scrolling to your one page website with jQuery
Kevin Powell
Let's learn Bootstrap 4
Kevin Powell
How I approach designing a website - my thought process
Kevin Powell
Build a website with Bootstrap 4 - Part 1: The setup
Kevin Powell
Build a website with Bootstrap 4 - Introduction
Kevin Powell
Build a website with Bootstrap 4 - Part 2: Customizing Variables
Kevin Powell
More on: Tool Use & Function Calling
View skill →Related Reads
📰
📰
📰
📰
React Introduction
Dev.to · Karthick (k)
Why SnapDOM Beats html2canvas for DOM-to-Image Capture
Dev.to · Juan Martin
I built 42 landing page templates as single HTML files (no npm, no build step)
Dev.to · Segcam spa
Part 7B — Section 2 — React Event Handling Explained: Forms, Event Object & User Input.
Medium · JavaScript
🎓
Tutor Explanation
DeepCamp AI