Skip to content

Instantly share code, notes, and snippets.

@pjkelly
Created July 7, 2010 16:47
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save pjkelly/466938 to your computer and use it in GitHub Desktop.
Save pjkelly/466938 to your computer and use it in GitHub Desktop.
var amountVisible = function(element) {
var scroll_top = $(window).scrollTop();
var scroll_bottom = scroll_top + $(window).height();
var element_top = element.offset().top;
var element_bottom = element_top + element.height();
if (element_bottom > scroll_top && element_bottom < scroll_bottom) {
return element_bottom - scroll_top;
} else {
return scroll_bottom - element_top;
}
}
var fetchMatchingNavItem = function(section) {
return $('#' + $(section).attr('id') + '-link').parent();
}
var setCurrentClass = function(item) {
item.addClass("current");
item.siblings("#nav li").removeClass("current");
}
var determineCurrentNodeAndSetNav = function() {
var node = null;
var elements_in_view = $('.scroll-item:in-viewport');
if (elements_in_view.get(0).id == 'header') {
node = elements_in_view.get(0);
} else {
elements_in_view.each(function(i){
var current_element = $(this);
if (node == null || amountVisible(current_element) >= amountVisible(node)) {
node = current_element;
}
});
}
current_index = $('.scroll-item').index(node);
if (node && node.id == 'header') {
$('#crushlovely #nav ol li').removeClass('current');
} else {
setCurrentClass(fetchMatchingNavItem(node));
}
}
$(document).ready(function() {
// Original concept borrowed from Pictory: http://www.pictorymag.com
var sections = $('.scroll-item');
var current_index = 0;
var node;
$(window).scroll(function () {
determineCurrentNodeAndSetNav();
});
$('#crushlovely #nav #logo, #coda #pop-back-up').click(function(e){
$.scrollTo('#header', 800);
node = $('#header');
current_index = sections.index(node);
e.preventDefault();
});
$('#crushlovely #nav ol li').click(function(e){
var target = $(this).children('a').get(0).href.split('#')[1];
$.scrollTo('#' + target, 800);
node = $('#' + target);
current_index = sections.index(node);
e.preventDefault();
});
$('#crushlovely .scroll-link').click(function(e){
var anchor = $(this);
var target = anchor.attr('href').split('#')[1];
var nav_item = $($('#' + target + '-link').parent())
$.scrollTo('#' + target, 800);
node = $('#' + target);
current_index = sections.index(node);
e.preventDefault();
});
$(document).keydown(function(e){
switch(e.keyCode){
case 39:
node = sections[++current_index];
if (node) {
$.scrollTo(node,800);
} else {
current_index = sections.length-1;
}
break;
case 37:
node = sections[--current_index];
if (node) {
$.scrollTo(node,800);
} else {
current_index = 0;
}
break;
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment