Adrian Adrian - 1 month ago 4
CSS Question

jQuery window scroll, on scoll down goes back up

Using jQuery scroll function to create a sticky header and sometimes on a specific height (i guess) when I scroll down, goes back to top of page.

Recorded this: http://take.ms/s9mGh8

This is my function:

$(window).scroll(function(e){
$('#main').toggleClass('fixed', $(this).scrollTop() > $('#header').height()+25);
});


How can I fix this?

Answer

The problem is that fixed elements doesn't take space in the DOM. So what happening here is that your header take space, you scroll the page, set the header with position:fixed so it doesn't take space anymore, all your elements move up and the scrollbar disappear.

To prevent that behavior, you need to add the "missing height" to the document when changing the class. A commun technique, used by StickyKit for example, if to add a placeholder div.

You can see a basic code here : https://jsfiddle.net/jaL765t1/

var flag = false;
$(window).scroll(function(e){
  var passed_point = $(this).scrollTop() > $('#header').height()+25;

  if(passed_point && !flag){
    var surrogate = $('<div>', {
        'class' : 'js-surrogate',
        css : {
        height : $('#header').height()
      }
    });
    $('#header').before( surrogate );
    $('#main').addClass('fixed');

    flag=true;
  }else if(!passed_point && flag){
    $('#main').removeClass('fixed');
    $('#header').prev('.js-surrogate').remove();
    flag=false;
  }  
});

Of course, this code is not good, but you can easily use it as a starting point.

Comments