patternjavascriptMinor
jQuery navbar scrollTop position
Viewed 0 times
scrolltopjquerypositionnavbar
Problem
I have this code, but I not the best to javascript/jQuery so are there any out there who can optimize this code?
$(function(){
var pos = $("header").offset().top;
$(document).scroll(function(){
if($(this).scrollTop() - 10 > pos)
{
$('header').addClass("filled");
} else {
$('header').removeClass("filled");
}
});
});Solution
I would write this like:
$(function(){
var header = $('header');
var threshold = header.offset().top;
$(document).scroll(function(){
header.toggleClass('filled', $(this).scrollTop() - 10 > threshold);
});
});Code Snippets
$(function(){
var header = $('header');
var threshold = header.offset().top;
$(document).scroll(function(){
header.toggleClass('filled', $(this).scrollTop() - 10 > threshold);
});
});Context
StackExchange Code Review Q#155912, answer score: 9
Revisions (0)
No revisions yet.