Reputation: 23
So i'm trying to learn javascript and jQuery. I was coding a project website and wanted to make the nav smaller and transparent as they scroll around the page. i wrote this and it works fine `
$(document).scroll(function(){
$('.nav').css({"opacity": "0.85", "height": "55px"});
$('.nav-container').css({"margin-top": "-13px", "font-size": "1.4em"})
});
`
But i want it to revert back to normal when they scroll all the way to the top. There doesn't seem to be a jQuery event for this.
Upvotes: 0
Views: 52
Reputation: 1376
I have updated your jsfiddle here
I just changed your .scroll()
function:
$(document).scroll(function () {
var scroll = $(this).scrollTop();
if(scroll > 0){
$('.nav').addClass('scrolled');
$('.nav-container').addClass('scrolled');
} else if(scroll == 0){
$('.nav').removeClass('scrolled');
$('.nav-container').removeClass('scrolled');
}
});
and added this css:
.nav.scrolled {
opacity:0.85;
height:55px;
}
.nav-container.scrolled {
margin-top:-13px;
font-size:1.4em;
}
Upvotes: 0
Reputation: 253318
I'd personally suggest:
$(document).scroll(function () {
// select the relevant elements:
$('#nav, .nav-container')[
// if the window is at the 'top', we use the 'removeClass' method,
// otherwise we use 'addClass':
$(window).scrollTop() == 0 ? 'removeClass' : 'addClass'
// and pass the 'scrolled' class-name to the method:
]('scrolled');
});
With the CSS:
.nav.scrolled {
opacity: 0.85;
height: 55px;
}
.nav-container.scrolled {
margin-top: -13px;
font-size: 1.4em;
}
This also uses corrected (valid HTML).
References:
Upvotes: 1