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"); } }) 
Sign up to request clarification or add additional context in comments.

3 Comments

Try to add some explanation of what you changed an why you changed it.
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.
Subtract jQuery('#fix-me').offset().top with 38 -> if(jQuery('#fix-me').offset().top - 38 <= jQuery(window).scrollTop())

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.