Stick element at the top

Arun - 09/02/2020 8:35 AM

Stick element at the top

Files 2

stick-element.html
html
<div id="sidebar" style="width:270px;"> 
  <div id="scroller-anchor"></div> 
  <div id="scroller" style="margin-top:10px; width:270px"> 
    Scroller Scroller Scroller
  </div>
</div>
stick-element.js
javascript
$ = jQuery;
 
function moveScroller() {
   var $anchor = $("#scroller-anchor");
    var $scroller = $('#scroller');
 
    var move = function() {
    	
        var st = $(window).scrollTop();
        var ot = $anchor.offset().top;
        var ol = $scroller.offset().left;
        if(st > ot) {
            $scroller.css({
                position: "fixed",
                top: "5px",
                left: ol
            });
        } else {
            if(st <= ot) {
                $scroller.css({
                    position: "relative",
                    top: "",
                    left: ""
                });
            }
        }
    };
    $(window).scroll(move);
    move();
}
 
 $(function() {
    moveScroller();
  });