Skip to content

Instantly share code, notes, and snippets.

@pork-chop
Created November 17, 2017 20:42
Show Gist options
  • Save pork-chop/caf976140158c5baef85521ce7c3fa1f to your computer and use it in GitHub Desktop.
Save pork-chop/caf976140158c5baef85521ce7c3fa1f to your computer and use it in GitHub Desktop.
Very verbose JS... how to loop more efficiently?
$(window).scroll(function() {
var scroll = $(window).scrollTop(); // how many pixels you've scrolled
var offset31 = $('#post-31').offset().top - $navHeight;
var height31 = $('#post-31').height();
var post31 = offset31 + height31;
var offset37 = $('#post-37').offset().top - $navHeight;
var height37 = $('#post-37').height();
var post37 = offset37 + height37;
var offset40 = $('#post-40').offset().top - $navHeight;
var height40 = $('#post-40').height();
var post40 = offset40 + height40;
var offset46 = $('#post-46').offset().top - $navHeight;
var height46 = $('#post-46').height();
var post46 = offset46 + height46;
var offset49 = $('#post-49').offset().top - $navHeight;
var height49 = $('#post-49').height();
var post49 = offset49 + height49;
var offset51 = $('#post-51').offset().top - $navHeight;
var height51 = $('#post-51').height();
var post51 = offset51 + height51;
if( scroll > (offset31 - $navHeight) && scroll < post31) {
$('li.menu-item').removeClass('current');
$('li.post-31').addClass('current');
// console.log('first if -- scroll: ' + scroll + ', offset31: ' + offset31 + ', height31: ' + height31)
} else if ( scroll > (offset37 - $navHeight) && scroll < post37) {
$('li.menu-item').removeClass('current');
$('li.post-37').addClass('current');
// console.log('second if -- scroll: ' + scroll + ', offset37: ' + offset37 + ', height37: ' + height37)
} else if ( scroll > (offset40 - $navHeight) && scroll < post40) {
$('li.menu-item').removeClass('current');
$('li.post-40').addClass('current');
// console.log('third if -- scroll: ' + scroll + ', offset40: ' + offset40 + ', height40: ' + height37)
} else if ( scroll > (offset46 - $navHeight) && scroll < post46) {
$('li.menu-item').removeClass('current');
$('li.post-46').addClass('current');
// console.log('fourth if -- scroll: ' + scroll + ', offset46: ' + offset46 + ', height46: ' + height37)
} else if ( scroll > (offset49 - $navHeight) && scroll < post49) {
$('li.menu-item').removeClass('current');
$('li.post-49').addClass('current');
// console.log('fifth if -- scroll: ' + scroll + ', offset49: ' + offset49 + ', height49: ' + height37)
} else if ( scroll > (offset51 - $navHeight) && scroll < post51) {
$('li.menu-item').removeClass('current');
$('li.post-51').addClass('current');
// console.log('sixth if -- scroll: ' + scroll + ', offset51: ' + offset51 + ', height51: ' + height37)
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment