- This topic is empty.
Viewing 6 posts - 1 through 6 (of 6 total)
Viewing 6 posts - 1 through 6 (of 6 total)
- The forum ‘JavaScript’ is closed to new topics and replies.
The forums ran from 2008-2020 and are now closed and viewable here as an archive.
Home › Forums › JavaScript › Sliding Nav Bar? Do I need JS?
I haven’t learned much JS yet, but can I make a nav bar like this one with just css?
Which area are you talking about, specifically?
Errr. The main navigation bar at DCcomics is what I’m trying to replicate. When it scrolls down past a certain point, it becomes shorter and then is fixed to top.
Ah! I see it now. Using the word ‘sliding’ threw me off. What you’re looking for is a ‘sticky’ nav. You’ll need to use JS to calculate the user’s scroll position and then decide at what point you’ll want it to become sticky.
In this case, you’d want to do something like this:
var cutOff = headerHeight - navHeight;
In this case, cutOff
is the point at which when a user is scrolling the top of the window will hit the top of the nav.
You can get the user’s scroll position like this:
var scrollPosition = $(window).scrollTop();
Then you’ll just need a simple conditional:
if( scrollPosition > cutOff ) {
$('nav').addClass('sticky');
} else {
$('nav').removeClass('sticky');
}
Then in your CSS file you’d have a sticky class:
.sticky {
position: fixed;
}
Lots of other small stuff would need to be done, but that is the basic concept. I’m sure there are some tutorials around the web for ‘sticky nav’. Just make sure you don’t just grab some super bloated code from somewhere!
Ok, thats very helpful. Thanks:)
As per Mr. Jamy, it’s better to use:
var scrollPosition = $(window).scrollTop();
https://twitter.com/jamygolden/status/361904984947834880
I’ve updated my previous post.