Javascript var doesn't apply the height of an ul as a value

So I made a script that makes my navigation bar stick to the top when scrolled below it. The problem was that my content 'jumped' up because of the space becoming available due to the navigation bars fixed property. Now I tried to fix it which worked when I gave it a % or px value via JS/JQuery. But once I tried giving it the proper value, which is the height of the navigation bar nothing worked anymore. So I guess the declaration must we wrong or am I missing a .toString() somewhere? Thank you.

Note that #Nav is the height of a ul, and not a div, in case that'd matter.

$(document).ready(function() {
  var stickyNavTop = $('#Nav').offset().top; //var = space between Navbar and top of the page

  var stickyNav = function() {
    var scrollTop = $(window).scrollTop(); //var = top of viewport where the user currently is.
    var NavbarHeight = document.getElementById('#Nav').clientHeight; //var = height Navbar
    if (scrollTop > stickyNavTop) {
      $('#Nav').addClass('FixedNav'); //adds class 
      $('#Content').css("margin-top", NavbarHeight); //edits class
    } else {
      $('#Nav').removeClass('FixedNav'); //removes class
      $('#Content').css("margin-top", "auto"); //edits class
    }
  };

  stickyNav();

  $(window).scroll(stickyNav());
});

Answers 1

  • There is a possibility that it does matter that you are using an ul and not a div container - if your ul contains floated li elements then it's height:

    The container of a floated element is shrunken so that other inline elements will flow around it (as per specs).

    See: Why for li with style float:left browser evaluates the height of the ul element to 0?

    Try adding an explicit height to the ul (e.g: height: 152px;) or overflow:hidden; to get the browser to calculate the height of the ul correctly.

    Edit: per your comment, that the script only works when have margin-top set as 10%, I think I am on the right track here. Hope it helps you.


Related Articles