Enhanced jQuery Prototype - Version 2
I revisited this challenge and improved the functionality for a smoother experience.
Below is the revised jQuery script:
init = {
previousTop: 0,
headerHeight: 52
}
$(window).scroll(init,function () {
var currentTop = $(window).scrollTop();
var scrollMax = $(document).height() - $(window).outerHeight(true);
var bodyHeight = $(window).outerHeight(true);
var scrollType = "";
if (currentTop < init.previousTop) {
$(".offset b").text(currentTop);
$(".offset em").text("Up");
scrollUp = true;
} else {
$(".offset b").text(currentTop);
$(".offset em").text("Down");
scrollUp = false;
}
if (scrollUp == true) {
$(".header").css({"color": "blue"});
$(".header").css({"top": currentTop});
} else {
$(".header").css({"color": "yellow"});
if (scrollMax - currentTop < init.headerHeight) {
$(".header").css({"top": 0});
}
}
/* Optional - to display values of various attributes */
$(".previousTop b").text(init.previousTop);
$(".headerHeight b").text(init.headerHeight);
$(".bodyHeight b").text(bodyHeight);
$(".scrollMax b").text(scrollMax);
init.previousTop = currentTop;
});
You can view the updated demo on this link: http://jsfiddle.net/audetwebdesign/gmkum/
Functionality Overview
This improvement focuses on four key elements that enhance user interaction.
(1) The code snippet regarding currentTop < init.previousTop
helps determine scrolling direction, ensuring smooth navigation.
(2) When scrolling upwards, the header is positioned at the window's top, maintaining visibility.
(3) On downward scrolls, the header remains in place as it scrolls off-screen with the content due to absolute positioning.
(4) Notably, near maximum scroll limits, adjustments ensure the header transitions smoothly even with limited screen space remaining.