Navbar sticks to top before reaching scroll point and won't return until reload of page

120
January 17, 2018, at 03:29 AM

I'm trying to implement a sticky navbar to a webpage I'm making.

Currently when I first enter any page the navbar will sit on its intended spot, but as soon as I scroll it snaps to the top and will stay there however I scroll. (sometimes it snaps back down when you scroll to the top)
The intended behavior is to stick whenever you scroll past the navbar position.

But if you reload the page once or twice it will start working just as intended.

Code is written in jquery:

// JavaScript Document
$(document).ready(function() {
    fixNavbar();
});
//Fixed navbar on scroll past navbar pos
function fixNavbar() {
    var navOffset = $(".navigation").offset().top;
    $(window).scroll(function(){
      var nav = $(".navigation"), scroll = $(window).scrollTop();
      if (scroll >= navOffset) nav.addClass("nav-fix");
      else nav.removeClass("nav-fix");
    });
}

CSS is pretty simple: only a class with position: fixed;

Here is the page in action: http://aktersnurra.se
Thanks in advance for the help!

Answer 1

The image on top of the navigation bar is still loading when you set up your scroll event.

This means that the navOffset often gets incorrect values.

You have to replace your

$(document).ready(function () {

into

$(window).on('load', function () {

Which waits untill the whole page including images is loaded.

Answer 2

Your navOffset is getting the wrong value at times

READ ALSO
Collapse non-active Div's when hyerlink clicked

Collapse non-active Div's when hyerlink clicked

I have a web page https://websiterightco

135
vs2017 “the process or thread has changed” issue

vs2017 “the process or thread has changed” issue

I know this question has been asked before here: The process or thread has changed since last step and The process or thread has changed since last step (Visual Studio) as well as othersBut before yesterday it never happened to me before, The code is basically...

263
Cross browser issue with jquery a hyperlink

Cross browser issue with jquery a hyperlink

Here is the link as other I do not know how to explain [1] https://turisolnet/costa-blanca-holiday-rentals/benissa/san-jaime-19m-139/details [1]

194
It's possible to call html and css tags inside a text file?

It's possible to call html and css tags inside a text file?

First question here! So, i'm at the beginning of my studies and i have searched on Google and didn't found anything about this scenario:

147