Reputation: 533
I have built the prototype that I'll use for my site header, it is basically a simple navigation that on scroll re-appears on screen in a fixed position (sticky nav). I firstly acheived this by having two tags in the markup but ideally I'd liek to acheive this using only one.
Here's my codepen
If you slowly scroll down you should see what I'm trying to achieve here. Heres my javascript:
$(window).scroll(function() {
if ($(this).scrollTop() > 60){
$('.main-header').addClass("sticky-header");
}
else{
$('.main-header').removeClass("sticky-header");
}
if ($(this).scrollTop() > 160){
$('.main-header').addClass("sticky");
}
else{
$('.main-header').removeClass("sticky");
}
});
There is probably a better way of achieving this using a slightly different approach? I don't like the fact I'm testing for two instances of scroll top, only did this because firstly I need a way to apply the positioning of the header, apply the margin value which does the snazzy transition as if it's moving downwards from the top of the page.
Upvotes: 0
Views: 839
Reputation: 130
Replace Your javascript with the below one: you will get nice scroll
$(window).scroll(function() {
if ($(this).scrollTop() > 0){
$('.main-header').addClass("sticky-header");
}
else{
$('.main-header').removeClass("sticky-header");
}
if ($(this).scrollTop() > 160){
$('.main-header').addClass("sticky");
}
else{
$('.main-header').removeClass("sticky");
}
});
Upvotes: 1