1

I have the following code. It set a filter bar in a search results page in a fixed position in the window after scrolling down to a certain point:

var docked;
var filters = document.getElementById('filters');
var init = filters.offsetTop;

function scrollTop() {
  return document.body.scrollTop || document.documentElement.scrollTop;
}

window.onscroll = function () {
  if (!docked && (init - scrollTop() < 0)) {
    filters.style.top = 0;
    filters.style.position = 'fixed'; 
    filters.className = 'docked'; 
    docked = true;
  } else if (docked && scrollTop() <= init) { 
    filters.style.position = 'absolute'; 
    filters.style.top = init + 'px';
    filters.className = filters.className.replace('docked', ''); 
    docked = false;  
  }
}

My issue is (and it's more curiosity) - if I place this code at the top of my file (in the <head>), it doesn't work at all. The filter section doesn't scroll with the window as it should. However, when I place this code at the bottom of the file (right above the closing </body> tag), it works just fine.

Why is this? Does this have something to do with the way the code works? Or could it be just a quirk or bug in the rest of my file causing this?

Brian Phillips
  • 4,302
  • 2
  • 25
  • 40

2 Answers2

6

Wrap your assignments in window.onload = function(){ /* your code here */ }; and it will run. The reason being that your assignment of var filters = document.getElementById('filters'); comes back as undefined since that element does not exist during page load at the time you reference it.

Example:

var docked;
var filters;
var init;
window.onload = function(){
 filters = document.getElementById('filters');
 init = filters.offsetTop;
};
Travis J
  • 81,153
  • 41
  • 202
  • 273
0

if you do this, it should work:

$(document).ready(window.onscroll = function () {
  if (!docked && (init - scrollTop() < 0)) {
    filters.style.top = 0;
    filters.style.position = 'fixed'; 
    filters.className = 'docked'; 
    docked = true;
  } else if (docked && scrollTop() <= init) { 
    filters.style.position = 'absolute'; 
    filters.style.top = init + 'px';
    filters.className = filters.className.replace('docked', ''); 
    docked = false;  
  }
}
);
Nathan
  • 24,586
  • 4
  • 27
  • 36