Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // buffer to prevent positioning changes from happening right at edge of screen
- var buffer = 100;
- // initial window offset
- var prevScrollPosition = window.pageYOffset;
- // get Alert Bar height if present
- if($('#alertApp').length) {
- var alertBarHeight = $('#alertApp').outerHeight();
- } else {
- var alertBarHeight = 0;
- }
- // get WP Admin Bar height if present
- if($('#wpadminbar').length) {
- var wpAdminBarHeight = $('#wpadminbar').outerHeight();
- } else {
- var wpAdminBarHeight = 0;
- }
- // combined height of header + any ancillaries (alert bar, admin bar, etc)
- var headerHeight = $('header').outerHeight();
- var delta = headerHeight + alertBarHeight + wpAdminBarHeight;
- var initialHeaderOffset = alertBarHeight + wpAdminBarHeight;
- var distanceFromTop, firstScroll, headerTopOffset, scrollPosition;
- // determine if page is at top or lower down the page (i.e. refreshed) on page load
- if($(window).scrollTop() == 0) {
- firstScroll = true;
- } else {
- firstScroll = false;
- }
- $(window).scroll(function() {
- scrollPosition = $(this).scrollTop();
- // if scrolling up -> show menu
- if (prevScrollPosition > scrollPosition) {
- $('header').addClass("sticky-header").css({"top": headerTopOffset});
- var headerPosition = $('header').offset().top - $(this).scrollTop();
- if(headerPosition >= 0) {
- $('header').css({"position": "fixed", "top": 0});
- firstScroll = false;
- distanceFromTop = window.pageYOffset;
- }
- // if scrolling down from the top of the site, reposition header just above the
- // screen once user scrolls past it and any ancillaries (alert bar, admin bar, etc)
- } else if (firstScroll && scrollPosition > delta + buffer) {
- headerTopOffset = scrollPosition - (delta + buffer);
- $('header').css({"position": "absolute", "top": headerTopOffset});
- $('body').css({"padding-top": $('header').outerHeight()});
- firstScroll = false;
- // if scrolling down after header is sticky, change positioning to absolute so it scrolls off screen
- // - - - THE PROBLEM MAY BE HERE - - -
- } else if (!firstScroll) {
- $('header').css({"position": "absolute", "top": distanceFromTop});
- // once scrolled past the header, position it just above the window so it
- // scrolls back into view when you scroll up
- if(($('header').offset().top + headerHeight + buffer) < scrollPosition) {
- headerTopOffset = scrollPosition - (delta + buffer);
- $('header').removeClass("sticky-header");
- }
- }
- prevScrollPosition = scrollPosition;
- // if scrolled all the way to the top -> reset back to original positions
- if(scrollPosition <= initialHeaderOffset) {
- $('header').css({"position": "relative"}).removeClass("sticky-header");
- $('body').css({"padding-top": 0});
- firstScroll = true;
- }
- });
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement