2

I tried to fixed an element on top, when this element touch the top of the window, when the user scroll down. On scroll down everything works (added a class with the fixed position), but when I scroll up doesn't work. but i don't understand why :( i created a jsfiddle with this code: http://jsfiddle.net/8h4knr9r/

$(window).scroll(function () {
     var distance = $('#navigation-sections').offset().top;

     if ($(window).scrollTop() >= $('#navigation-sections').offset().top) {
         $('#navigation-sections').addClass("affix");

     } else {
         $('#navigation-sections').removeClass("affix");
     }
 });

thanks

mattia
  • 591
  • 2
  • 7
  • 22

1 Answers1

5

You need to store the initial distance outside the scroll function - otherwise it will get recalculated every scroll. Here is the working fiddle: http://jsfiddle.net/donal/8h4knr9r/5/

The JS should look like this:

var distance = $('#navigation-sections').offset().top; 

$(window).scroll(function () {

     if ($(window).scrollTop() >= distance) {
         $('#navigation-sections').addClass("affix");

     } else {
         $('#navigation-sections').removeClass("affix");
     }
 });
Donal
  • 31,121
  • 10
  • 63
  • 72
  • thanks. i noticed that on tablet and mobile the performance is very slow. the position fixed is changed only when the scroll is finished. how can I get better this? is it possible? thanks – mattia Mar 04 '15 at 16:13
  • Try the gesturechange event. See here: http://stackoverflow.com/a/17195346/379855 – Donal Mar 05 '15 at 12:32