DDiran
DDiran

Reputation: 573

Resetting navbar state after page reload

Pretty basic question (I think) about a page being refreshed.

So I have a fixed navbar which resizes and changes colour and does all sorts of fancy things when you scroll down. Problem is, when you refresh the page the navbar will "refresh" as well even if you are still scrolled down it will look like it did if you were at the top of the page.

Using jQuery 2.x here's what I've got:

$(window).scroll(function() {
   if ($(document).scrollTop() > 50) {
       $('nav').addClass('shrink');
       $('#enquire-btn').addClass('btn-shrink');
       $('#logo').css("max-height", "70px")
       $('#logo-link').css("padding-top", "7px")
   } else {
       $('nav').removeClass('shrink');
       $('#enquire-btn').removeClass('btn-shrink');
       $('#logo').css("max-height", "100px")
       $('#logo-link').css("padding-top", "15px")
   }
});

Upvotes: 0

Views: 1413

Answers (2)

intentionally-left-nil
intentionally-left-nil

Reputation: 8284

My first suggestion is to listen to the $(window).load() event and then re-calculate your state based on the scroll top.

Depending on the browser implementation of scroll-after-refresh, you may need to add a timeout.

A separate option would be to scroll the document to the top right before the refresh so it doesn't scroll again after the reload:

$(window).on('beforeunload', function() {
    $(window).scrollTop(0);
});

Upvotes: 1

c-bro
c-bro

Reputation: 486

I think the issue is this function is only triggered on scroll. When you reload the page the function has never been called. You could try changing it to something like this:

$(window).scroll(ScrollChange);
function ScrollChange(){
if ($(document).scrollTop() > 50) {
       $('nav').addClass('shrink');
       $('#enquire-btn').addClass('btn-shrink');
       $('#logo').css("max-height", "70px")
       $('#logo-link').css("padding-top", "7px")
   } else {
       $('nav').removeClass('shrink');
       $('#enquire-btn').removeClass('btn-shrink');
       $('#logo').css("max-height", "100px")
       $('#logo-link').css("padding-top", "15px")
   }
}

$( document ).ready(function() {
    ScrollChange();
}

This way your function also gets triggered on page load.

Upvotes: 3

Related Questions