javascript - Sticky Header - buggy jumping on scroll -


i have specific problem on making sticky header jquery. tried commonly used snippets around web, perceived same buggy thing everywhere.

at specific document height (scrollable until little more calling of sticky-effect) sticky header jumps between position: fixed , position: static.

html:

<header>   <div id="not-sticky"></div>   <div id="sticky"></div> </header> <div id="content"> ... 


jquery:

var $sticky = $("#sticky"); var offset = $sticky.offset(); var stickytop = offset.top; var windowtop = $(window).scrolltop(); $(window).scroll(function() {   windowtop = $(window).scrolltop();   if (windowtop > stickytop) {     $sticky.css({       position: 'fixed',       top: 0     });   }   else {     $sticky.css({       position: '',       top: ''     });   } }); 


css:

header {   width: 100%; }  #not-sticky {   padding: 50px 0;   width: 100%; }  #sticky {   padding: 24px 0;   position: relative;   width: 100%;   z-index: 25; } 


i tried margin-bottom on #not-sticky same height #sticky keep constant document-height, same jumpy-sticky-effect occurred.

any idea fix thing?

scroll fires many times , trying set element style & inevitably create jumps (even barely noticeable still jaggy).

the best way i've found

  1. clone our element,
  2. make clone fixed
  3. play clone's visibility style.

pure js:

;(function(){ /* sticky */      var sticky  = document.getelementbyid("sticky"),        sticky2 = sticky.clonenode(true);      sticky2.style.position = "fixed";    document.body.appendchild(sticky2);      function stickit(){      sticky2.style.visibility = sticky.getboundingclientrect().top<0 ? "visible" : "hidden";    }      stickit();    window.addeventlistener("scroll", stickit, false );  }());
#sticky{    height:100px;    background:#ada;    height:50px;    position:relative;    /* needed clone: */    top:0;     width:100%;  }      /* demo: */  *{margin:0;padding:0;}  #content{height:2000px; border:3px dashed #444;}  h1{padding:40px; background:#888;}
<h1>logo</h1>  <div id="sticky">sticky header</div>  <div id="content">lorem ipsum...<br>bla bla</div>

so when see "header" fix, that's our fixed clone getting visible on-top.


Comments

Popular posts from this blog

c# - DetailsView in ASP.Net - How to add another column on the side/add a control in each row? -

javascript - firefox memory leak -

Trying to import CSV file to a SQL Server database using asp.net and c# - can't find what I'm missing -