Here is an adapted version from dfsq's answer, which is the most elegant and simple solution I've found so far:
var myTop = document.getElementById('freeze').offsetTop;
var origClass = freeze.className;
window.onscroll = function() {
var y = (document.documentElement && document.documentElement.scrollTop) || document.body.scrollTop;
if (y >= myTop) {
freeze.className = origClass +' stick';
}
else {
freeze.className = origClass;
}
};
// Note that I barely have javascript knowledge, so the modification, even if it works, might be far from optimal. I'm open to improvements.
Main differences are:
- variable name changed to avoid ambiguity (see comments of that answer).
- additional variable and modification inside
if/else
in order to allow using it with tags with an existing class already assigned.
The only issue remaining is that at the moment when the div is fixed, there is a kind of 'jump' in the flow. This is easily seen in the original jsfiddle if adding any text (for instance <p>See how I jump!</p>
) a few lines below the div that is sticked.