How to make an animated sticky header with CSS and JavaScript!

Coder Coder · Beginner ·🌐 Frontend Engineering ·7y ago

Key Takeaways

Builds a sticky header with CSS and JavaScript

Full Transcript

hey everyone in this tutorial we're going to make a simple sticky header for our website first build the sticky header using HTML and CSS and second we'll add an animation effect so that when you scroll down the page the header will shrink using CSS transitions and JavaScript alright let's get started to start off we just have a very basic web page here with a header up at the top and then some main content down at the bottom when we scroll down the page the header Scrolls off the screen just like the rest of the content we're going to use some CSS to make the header sticky and that it will stick to the very top of the page and remain visible even when we scroll down to edit our CSS let's open up our code editor we're using the vs code in our project files we have an index.html file a style dot CSS file in a script J's file let's look at the index.html file up here we have the mark-up for the header we're going to add some CSS styles for this header element so let's look at our style of CSS file here's the header element in order to make the header a sticky header we're going to add a couple of CSS properties the first one is position fix this will make the header element fixed in any position that you want on the page we want to fix it to the top so we're also going to add a top of 0 pixels property to the header this will make sure that the header will be 0 pixels from the top or at the very top now let's save this and let's look back at our web page to see what it looks like now ok when we scroll down the page we see that the header is indeed fixed up to the top just like we wanted however you can also see that the regular content is kind of under the header this is because the position fixed property takes the header out of the normal flow of content in the page so the rest of the content behaves as if the header doesn't even exist what we want to do now is kind of push down the main content to a height equal to the height of the header so that it will start directly under the header let's see what the height of the header is okay it looks like it is 80 pixels tall so we're going to edit the regular content what we want to do is add some CSS to this section with a class of content let's go back into our code editor and look for that element which we have here at the bottom so I'm just going to add a margin top of 80 pixels which again is how tall that header is save that and reload the page okay now it looks like the content is starting in the right place and when we scroll down we see that the header is indeed sticky and it's always visible so this is your basic sticky header now we're gonna go one step further and use some more CSS and a little bit of JavaScript to make the header a little bit more fancy what we're going to do is use JavaScript to detect when you scroll past the top of the page and when that happens we're going to decrease the height of the header using some CSS classes and transitions there's two reasons that we're going to do this the first is that especially if you're on mobile you really don't want your header to take up too much vertical space because there isn't a lot of vertical real estate especially on your phone the second reason is that having a smooth animation just increases the the quality of your user experience on the website and it gives your website a bit extra layer of polish now let's go back to our code editor and look at our JavaScript file I've already added some JavaScript for the functionality that we're going to build at the bottom we have an add event listener function so that every time you scroll on the page it's going to run this callback function called check header above the check header function is going to run a throttle function from the lodash library and every time it fires it's going to write a message to the console if you haven't used lodash before it's a JavaScript library that works in conjunction with another JavaScript library underscore and they come with some very helpful pre-built functions that you can use among them this throttle function that I'm taking advantage of here now the reason that we need to use this throttle function is because when you are running a add eventlistener function and you're detecting your scroll events every time you scroll on your webpage it's going to fire this event a whole bunch of different times and you don't want you don't want to fire it so many times because eventually it could slow down in your browser actually let's do a quick little comparison test here I'm going to rewrite this check header function and remove the throttling part and we will do a little comparison and see how many times is going to fire okay now we have the check header function running without the throttling so let's save that and let's go back to our webpage and reload it and we will see in the console how many times that debug message will appear so this is one scroll so that's about maybe 15 15 events being fired every time I scroll so you can imagine if you're scrolling you know up and down the page someone could sort of end up slowing down your browser eventually because just in a few seconds you know we've done almost 200 events and the code that we have here is it's very simple it's just running this debug message but if you think about apps like say Instagram or Twitter every time you scroll down it's actually pulling more and more data and if you add that up with the number of users you know it's really going to slow down the app so even though this is a very simple example and we don't have to throttle it is better to throttle just for best practices sake so we've added the throttle function back in now let's do a little comparison test and see how many times that this debug message is written so now we're gonna scroll once and it only wrote it only wrote the debug message twice compared to 15 times the last time so even if we scroll up and down it's not firing that many times and this is this is really what you want to keep your code you know it's clean and and fast as possible okay let's get back to our code so we need to add a few more items to our JavaScript function here and let's just break this down step by step so the first thing we want to do in this cheque header function is to detect how far we've scrolled so let's just write a little comment here just say detect scroll position and then what we want to do is if we've scrolled let's say a bit past the header then we'll add that CSS class to the header we know that the header is 80 pixels tall so let's say if we've scrolled a little bit past the header if we've scrolled say 100 pixels and the sticky clasp to the header element and then if we've scrolled less than 100 pixels if not remove sticky class from header okay now one thing I like to do when in you know writing new CSS or JavaScript is I will actually test out my code in the browser console so let's do that with this first item here detects scroll position now if we open our dev tools which I have open here ready of course and there's a little console window down here you can actually write JavaScript and it will you know tell you if there's an error or you know what the value is and you can actually run javascript in the browser so the first thing we wanted to do is to check the scroll position and we can do that with window dot scroll y Y meaning the vertical axis so let's see what this says it says 0 which is correct because we're all the way to the top so let's try scrolling down a bit and then re-firing that ok now it says something greater than 0 to 49 point 5 which means it's detected that we've scrolled down 249 and 1/2 pixels I don't really want a decimal so I'm going to round this off and we can do that with math dot round and then the window dot scroll why Flitz fire that again and now it's a nice round number of 250 so we're going to take our JavaScript here and we're going to create a new variable called scroll position and I'll set that equal to the window scroll Y rounded value so this means every time we scroll it's going to check the scroll position now the next thing we want to do is figure out if we've scrolled past 100 pixels and we can do that by saying if scroll position that variable we just created if it's greater than a hundred then that means you've scrolled past 100 pixels so if that is the case we want to add sticky clasp to the header and to do that let's go back to our browser and we will go to our console window and we will try to get the header element and you should be able to do that by using document query selector and this left ear would be header and you can see that it's getting something so that means that this is correct it's accurate and we want to add the sticky clasp and to do that we can use the classlist dot add and then add the the class name which is sticky and let's fire this and see what happens and okay looks like the sticky clasp was added to the header and then of course we need to be able to remove that sticky clasp so should be remove and it looks like it was removed so we can add these two lines of script to our JavaScript file so okay the scroll position is greater than 100 we want to add sticky to the header class list and if not which means we'll add a little else statement here instead of adding we will remove the sticky clasp from the header okay so this is all the JavaScript that we need to do we've saved it and let's check in the browser and see if it works so we're gonna scroll down and looks like the sticky clasp was added to the header let's try scrolling back up and it was removed perfect now that we have successfully added and remove the sticky clasp from the header using JavaScript the next thing we want to do is add the CSS styles for when the header is sticky and again we can use the browser to kind of test out our CSS styles before we we save them to our files okay we wanted to decrease the height of the header when it has a sticky class we can see here that the height is already 40 pixels and I don't really want to decrease the height itself because that logo image is 40 pixels however I can decrease the the padding so we have a padding of 20 pixels and I would like to decrease that let's say from 20 to 10 pixels for the vertical padding we want to keep the horizontal padding as it is so we'll say 20 pixels it looks like we have some extra whitespace here I think that's from the body having a background color of this of white and not this gray purple color so I'm actually gonna go in and just kind of copy that background color and add it to the body so now we have the header which has the smaller padding of 10 pixels and let's just uncheck this and see the difference okay so that's a pretty good decrease I think and we'd mentioned before we also want kind of the smooth animation instead of the change happening kind of jerkily so we're going to add a transition property to the header as well transition property controls sort of the rate of change of any kind of property that you've changed for lack of a better word since we've changed the padding we're going to say it will affect the padding changes the second parameter that this takes is the duration or how long the change will take and I usually just start out with 300 milliseconds and the third parameter is the I guess the kind of type of animation progression that you have and default is usually just ease there's a bunch of different kinds but ease is just sort of basic you know general smooth animation so let's test this out again now that we have added the transition property and you can see when we check and uncheck the padding that the change is much smoother which is exactly what we want now let's copy this padding Stiles over back over to the code so this new padding is going to affect the header when it has a class of sticky so we will add that in here and then we also need to copy over this transition property and we want to affect the header like the default header element because we want this transition to happen whether or not the header has a sticky class so both adding and subtracting the padding we want its users transition and then of course we want to change that body background color so let's just add this here and that should be all the CSS that we need so let's go back to the browser and test this whole thing out okay we'll scroll down and see what happens and it looks like it is indeed changing when you scroll down which is great this is exactly what we wanted to happen and that's it for this sticky header tutorial congratulations for making it through if you want you can download all the project files for this from my github repo which I've linked to down below in addition if you want to stay connected and to date with new content you can follow me here on youtube or on instagram at the coder coder thanks for watching and we'll see you next time

Original Description

🔥 My course: Responsive Design for Beginners! https://coder-coder.com/responsive/ 💻 Become a full-stack web dev with Zero to Mastery: https://academy.zerotomastery.io/a/aff_338z7xnj/external?affcode=441520_ti97uk6b Build your own website header navigation bar that sticks to the top of the page, and animates as you scroll down the page. Summary: Step: Use CSS to make the header sticky. Step 2: Use JavaScript to detect if the user has scrolled down the page and add a CSS class. Step 3: Use CSS transitions to make the header animate smoothly on scroll. Blog post: https://coder-coder.com/sticky-header-animated Source code on GitHub: https://github.com/thecodercoder/simple-sticky-header _____________________________________ FOLLOW CODER CODER: Blog: https://coder-coder.com/ Instagram: https://www.instagram.com/thecodercoder Twitter: https://twitter.com/thecodercoder _____________________________________ #webdevelopment #html #css #livecoding #learntocode
Watch on YouTube ↗ (saves to browser)
Sign in to unlock AI tutor explanation · ⚡30

Playlist

Uploads from Coder Coder · Coder Coder · 2 of 60

1 How to Make a Super Simple HTML Website [Tutorial]
How to Make a Super Simple HTML Website [Tutorial]
Coder Coder
How to make an animated sticky header with CSS and JavaScript!
How to make an animated sticky header with CSS and JavaScript!
Coder Coder
3 How to get coding help by researching online
How to get coding help by researching online
Coder Coder
4 IG Live - Advice for beginner web developers
IG Live - Advice for beginner web developers
Coder Coder
5 Quick Start Guide to Parcel JS
Quick Start Guide to Parcel JS
Coder Coder
6 Build a responsive website with HTML & CSS - Part 1 [Live Coding]
Build a responsive website with HTML & CSS - Part 1 [Live Coding]
Coder Coder
7 Build a custom Linktree page for Instagram with HTML & CSS
Build a custom Linktree page for Instagram with HTML & CSS
Coder Coder
8 Gulp 4 Crash Course for Beginners
Gulp 4 Crash Course for Beginners
Coder Coder
9 How to use CSS position to layout a website
How to use CSS position to layout a website
Coder Coder
10 CSS: 4 Reasons Your Z-Index Isn't Working
CSS: 4 Reasons Your Z-Index Isn't Working
Coder Coder
11 Coding a landing page website with HTML & CSS
Coding a landing page website with HTML & CSS
Coder Coder
12 Learn web development as an absolute beginner
Learn web development as an absolute beginner
Coder Coder
13 How to write media queries in CSS
How to write media queries in CSS
Coder Coder
14 How to build a 2-column layout using flexbox | HTML/CSS
How to build a 2-column layout using flexbox | HTML/CSS
Coder Coder
15 How to build a simple responsive layout with CSS grid
How to build a simple responsive layout with CSS grid
Coder Coder
16 Write code faster in VS Code with Emmet shortcuts
Write code faster in VS Code with Emmet shortcuts
Coder Coder
17 How I setup VS Code for a beginners front-end workflow
How I setup VS Code for a beginners front-end workflow
Coder Coder
18 How to make a background-image transparent in CSS
How to make a background-image transparent in CSS
Coder Coder
19 Build a responsive website from scratch with HTML & CSS | Part 1: Navigation bar
Build a responsive website from scratch with HTML & CSS | Part 1: Navigation bar
Coder Coder
20 Animated Hamburger Menu in CSS/JS | Build a responsive website from scratch (Part 2)
Animated Hamburger Menu in CSS/JS | Build a responsive website from scratch (Part 2)
Coder Coder
21 Animated mobile menu with CSS/JS | Build a responsive website from scratch (Part 3)
Animated mobile menu with CSS/JS | Build a responsive website from scratch (Part 3)
Coder Coder
22 How to stay motivated when learning to code?
How to stay motivated when learning to code?
Coder Coder
23 Responsive hero | Build a responsive website from scratch (Part 4)
Responsive hero | Build a responsive website from scratch (Part 4)
Coder Coder
24 Responsive 4-column layout with flexbox | Build a responsive website from scratch (Part 5)
Responsive 4-column layout with flexbox | Build a responsive website from scratch (Part 5)
Coder Coder
25 Responsive 4-column layout with CSS Grid | Build a responsive website from scratch (Part 6)
Responsive 4-column layout with CSS Grid | Build a responsive website from scratch (Part 6)
Coder Coder
26 Building a footer using CSS Grid | Build a responsive website from scratch (Part 7)
Building a footer using CSS Grid | Build a responsive website from scratch (Part 7)
Coder Coder
27 Browsersync + Sass + Gulp in 15 minutes
Browsersync + Sass + Gulp in 15 minutes
Coder Coder
28 Responsive card UI with flexbox and hover effects | HTML/CSS
Responsive card UI with flexbox and hover effects | HTML/CSS
Coder Coder
29 CSS grid cards with animated hover effect | HTML/CSS
CSS grid cards with animated hover effect | HTML/CSS
Coder Coder
30 How I learned to code and landed a job (no CS degree!)
How I learned to code and landed a job (no CS degree!)
Coder Coder
31 Building the website for my course (coding timelapse)
Building the website for my course (coding timelapse)
Coder Coder
32 How to debug your code faster 🔥
How to debug your code faster 🔥
Coder Coder
33 Full timelapse + walkthrough of building my website
Full timelapse + walkthrough of building my website
Coder Coder
34 Your questions answered!! ✨100K Q&A✨
Your questions answered!! ✨100K Q&A✨
Coder Coder
35 Building a pricing block with HTML & PuRe CSS
Building a pricing block with HTML & PuRe CSS
Coder Coder
36 Use the Google Maps API to build a custom map with markers
Use the Google Maps API to build a custom map with markers
Coder Coder
37 Building an accordion with HTML, CSS & JS (Part 1)
Building an accordion with HTML, CSS & JS (Part 1)
Coder Coder
38 How to make your own VS Code theme!
How to make your own VS Code theme!
Coder Coder
39 How to build an accordion with HTML, CSS, and JavaScript (Part 2)
How to build an accordion with HTML, CSS, and JavaScript (Part 2)
Coder Coder
40 Life/channel update
Life/channel update
Coder Coder
41 Building a Light/Dark Dashboard, Part 1
Building a Light/Dark Dashboard, Part 1
Coder Coder
42 What is NPM, and why do we need it? | Tutorial for beginners
What is NPM, and why do we need it? | Tutorial for beginners
Coder Coder
43 Building a Node.js app (as a JavaScript noob) |  🔴 LIVE CODING
Building a Node.js app (as a JavaScript noob) | 🔴 LIVE CODING
Coder Coder
44 Free website project ideas for your portfolio #shorts
Free website project ideas for your portfolio #shorts
Coder Coder
45 How to add quickly emojis on Windows #shorts
How to add quickly emojis on Windows #shorts
Coder Coder
46 Building a Light/Dark Dashboard, Part 2
Building a Light/Dark Dashboard, Part 2
Coder Coder
47 Learn to code with these 4 free resources! #shorts
Learn to code with these 4 free resources! #shorts
Coder Coder
48 Learn flexbox with these 4 resources! #shorts
Learn flexbox with these 4 resources! #shorts
Coder Coder
49 [Typing sound] Comparing mechanical vs regular keyboard
[Typing sound] Comparing mechanical vs regular keyboard
Coder Coder
50 Building a Light/Dark Dashboard, Part 3
Building a Light/Dark Dashboard, Part 3
Coder Coder
51 what making web development tutorials is really like 😅 #shorts
what making web development tutorials is really like 😅 #shorts
Coder Coder
52 Generate website starter files with just one command!
Generate website starter files with just one command!
Coder Coder
53 emojis in code
emojis in code
Coder Coder
54 Stay motivated when coding: don't compare yourself with others #shorts
Stay motivated when coding: don't compare yourself with others #shorts
Coder Coder
55 Building a Light/Dark Dashboard, Part 4
Building a Light/Dark Dashboard, Part 4
Coder Coder
56 Coding motivation: slow and steady wins the race 🐢🏁
Coding motivation: slow and steady wins the race 🐢🏁
Coder Coder
57 Sass @import is being replaced with @use and @forward
Sass @import is being replaced with @use and @forward
Coder Coder
58 Coding motivation tip: keep your goal in mind
Coding motivation tip: keep your goal in mind
Coder Coder
59 How do websites work?
How do websites work?
Coder Coder
60 Building a Light/Dark Dashboard, Part 5
Building a Light/Dark Dashboard, Part 5
Coder Coder

Related Reads

📰
React Introduction
Learn the basics of ReactJS and how to build dynamic user interfaces with this popular JavaScript library
Dev.to · Karthick (k)
📰
Why SnapDOM Beats html2canvas for DOM-to-Image Capture
Learn why SnapDOM outperforms html2canvas for DOM-to-image capture and how to use it in your frontend projects
Dev.to · Juan Martin
📰
I built 42 landing page templates as single HTML files (no npm, no build step)
Learn how to create simple landing page templates as single HTML files without relying on npm or build steps, and why this approach matters for efficient web development
Dev.to · Segcam spa
📰
Part 7B — Section 2 — React Event Handling Explained: Forms, Event Object & User Input.
Learn React event handling for forms and user input to improve your frontend skills
Medium · JavaScript
Up next
Elementor Angie Ai Plugin Tutorial
Quick Tips - Web Desiign & Ai Tools
Watch →