Skip to content

Instantly share code, notes, and snippets.

@mpdroog
Created March 18, 2022 11:21
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mpdroog/3f5eb10e66a5b77ab219abaefc10b2dc to your computer and use it in GitHub Desktop.
Save mpdroog/3f5eb10e66a5b77ab219abaefc10b2dc to your computer and use it in GitHub Desktop.
// Small (vanilla) JS to make div scroll with the view
// Saving this code for historical purposes
// Note: In 2022 this is also possible with CSS through position: sticky
var dom = {
off: function ($node) {
var sum = $node.offsetTop;
if ($node.offsetParent) {
sum += dom.off($node.offsetParent);
}
return sum;
},
getId: function(id) {
var $node = document.getElementById(id);
if ($node === null) {
throw "Missing node with id=" + id;
}
return $node;
}
};
{
var $summary = dom.getId("js-summary");
var $foot = dom.getId("js-content-height");
var minoffset = dom.off($summary);
var maxoffset =
dom.off($foot) + $foot.offsetHeight - $summary.offsetHeight - minoffset;
console.log("summary.top.range", minoffset, maxoffset);
// state to filter out change
var lastScrollTop = window.scrollY;
var lastTimeout = null;
var loop = null;
var scroll = null;
var raf =
window.requestAnimationFrame ||
window.webkitRequestAnimationFrame ||
window.mozRequestAnimationFrame ||
window.msRequestAnimationFrame ||
window.oRequestAnimationFrame;
window.onresize = function () {
lastScrollTop = null;
$summary.style.top = 0;
minoffset = dom.off($summary);
maxoffset =
dom.off($foot) + $foot.offsetHeight - $summary.offsetHeight - minoffset;
};
scroll = function () {
var vertical_position = 0;
if (pageYOffset)
//usual
vertical_position = pageYOffset;
else if (document.documentElement.clientHeight)
//ie
vertical_position = document.documentElement.scrollTop;
else if (document.body)
//ie quirks
vertical_position = document.body.scrollTop;
maxoffset =
dom.off($foot) +
$foot.offsetHeight -
$summary.offsetHeight -
minoffset -
40; // Hardcoded? minus 40 b/c ticket-mention has bottom -40px
var newpos = vertical_position - minoffset;
var top = 0;
if (newpos > 0 && newpos < maxoffset) {
top = newpos;
} else if (newpos >= maxoffset) {
top = maxoffset;
}
$summary.style.top = top + "px";
};
loop = function () {
if (
lastScrollTop === window.scrollY ||
Math.abs(lastScrollTop - window.scrollY) < 20
) {
// no change, delay
raf(loop);
return;
}
if (lastTimeout) return;
lastTimeout = window.setTimeout(function () {
// change
lastScrollTop = window.scrollY;
lastTimeout = null;
scroll();
raf(loop);
}, 500);
};
if (raf) {
loop();
scroll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment