Fix on scroll but with varying screen size no set pixel distance

410 views Asked by At

I have a div with an image background thats height is 100% so it fills the screen on any device. At the bottom of the screen is then a navigation bar. When the page is scrolled I want the navigation bar to fix to the top of the screen at a set distance away from the top. I have tried using this JavaScript:

$(window).scroll(function(){
  if ($(this).scrollTop() > 587) {
      $('.hnav').addClass('hfixed');
  } else {
      $('.hnav').removeClass('hfixed');
  }});

It works fine on my screen but on any other screen it doesn't because the navigation changes distance from the top depending on the window size because of the 100% height image.

How can I get the navigation to fix in place when its a set distance from the top regardless of the window size??

Thanks

1

There are 1 answers

8
Sirikon On BEST ANSWER

You can get the element's position with element.getBoundingClientRect(), so you can add the 'hfixed' class once this returns a top value of 0:

var nav = $('.hnav');
var pos = nav.position();                      
$(window).scroll(function() {
    var windowpos = $(window).scrollTop();
    if (windowpos + 50 >= pos.top) {
        nav.addClass("hfixed");
    } else {
        nav.removeClass("hfixed");  
    }
});

EDIT:

Added an extra margin of 50px to the calc, because the top bar.

EDIT 2:

Changed the example, now it's based on this

EDIT 3:

Add the 50px margin because the top bar to the new example