Adrian Adrian - 1 year ago 87
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:

This is my function:

$('#main').toggleClass('fixed', $(this).scrollTop() > $('#header').height()+25);

How can I fix this?

Answer Source

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 :

var flag = false;
  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 );

  }else if(!passed_point && flag){

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download