Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sticky sidebar javascript without jQuery

Tags:

javascript

css

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.

like image 842
Opptatt Jobber Avatar asked Jun 16 '13 17:06

Opptatt Jobber


2 Answers

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.

like image 184
Niet the Dark Absol Avatar answered Nov 15 '22 11:11

Niet the Dark Absol


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)

like image 22
nice ass Avatar answered Nov 15 '22 12:11

nice ass