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
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:
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