How do you make a sticky vertical sidebar with stopper, but without jQuery? Are there any snippets/plugins? I don't need it to support older browsers.
I don't mean just position: fixed, it must stay in the same place and then start being sticky (fixed) when you've scrolled past a certain point. It must then stop following at the stop point.
Like http://stickyjs.com, but NOT jQuery. There are many jQuery plugins available.
Basically it's as easy as this:
window.onscroll = function() {
var sticky = document.getElementById('stickynav');
if( document.body.scrollTop+document.documentElement.scrollTop > 240)
sticky.className = "stuck";
else sticky.className = "";
};
Then just define styles in the .stuck
class that add things like position:fixed
to the element.
Here's an attempt that doesn't require position: fixed
changes, uses the element-document distance as reference and let's you scroll to the bottom:
var node = document.getElementById('side'), // your element
nodeOffs = node.offsetTop, // distance relative to its parent
parent = node;
// loop through parents to determine the distance relative to the document top
while(parent = parent.offsetParent)
if(parent.offsetTop)
nodeOffs += parent.offsetTop;
window.addEventListener('scroll', function(event){
// current scroll position relative to the body
var scrollPos = document.body.scrollTop;
if(scrollPos > nodeOffs){
// don't do anything if the elements height is larger than the
// remaining scroll content height (distance including)
if(scrollPos < (document.body.scrollHeight - node.clientHeight - nodeOffs))
node.style.top = (scrollPos - nodeOffs) + 'px';
}else{
node.style.top = '0px';
}
});
It's likely that this won't handle all possible cases (it doesn't take into account margins for example). That's why there's a plugin that you should use it if you don't want to tweak the js yourself....
(test)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With