j00m
j00m

Reputation: 501

Position fixed on scroll

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?!

Upvotes: 0

Views: 62

Answers (1)

Velid Duranović
Velid Duranović

Reputation: 182

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");
   }
})

Upvotes: 1

Related Questions