0

I am trying to fix a side nav when a user scrolls to a certain point. I am currently using:

        if(jQuery('#fix-me').offset().top <= jQuery(window).scrollTop()){
            var position = 38;
        }

This works well only I need it to kick in 38px from the top and not 0px

Im just not sure of the correct way to achieve this?!

1 Answer 1

1

If you want to set the element fixed when it is 38px before it hit the top of the document, you just need to subtract startPosition with 38. See code below. What I Recommend is to put element offset top in some variable, in our case it is startPosition

var startPosition = jQuery('#fix-me').offset().top;

$(document).on("scroll", function(){
   if(startPosition - 38 <= jQuery(window).scrollTop()){
     jQuery('#fix-me').addClass("fixed");
     //Add css styling
   }else{
     jQuery('#fix-me').removeClass("fixed");
   }
})
3
  • 1
    Try to add some explanation of what you changed an why you changed it.
    – Michel
    Commented Dec 7, 2020 at 12:00
  • 1
    Sorry may be my question isnt clear! if(jQuery('#fix-me').offset().top <= jQuery(window).scrollTop()){ I need this to be true 38px sooner than it currently is. So how do I add 38px to that IF statement.
    – j00m
    Commented Dec 7, 2020 at 12:03
  • Subtract jQuery('#fix-me').offset().top with 38 -> if(jQuery('#fix-me').offset().top - 38 <= jQuery(window).scrollTop()) Commented Dec 7, 2020 at 12:18

Not the answer you're looking for? Browse other questions tagged or ask your own question.