StickyNav - On Scroll Fix Div

In this example below you will see how to do a StickyNav - On Scroll Fix Div with some HTML / CSS and Javascript

Thumbnail
This awesome code was written by adamjoiner, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
Copyright adamjoiner ©
  • HTML
  • CSS
  • JavaScript
<!DOCTYPE html>
<html lang="en" >

<head>
  <meta charset="UTF-8">
  <title>StickyNav - On Scroll Fix Div</title>
  
  
  
      <link rel="stylesheet" href="css/style.css">

  
</head>

<body>

      and this<br>
    is<Br>
    above<br>
    <div id="productMenuBar" class="productMenuBar">
        LOGO
    </div>
    hello
    <br><BR><br>
    <br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br>
    <br><BR><br>world
    <br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br>
    <br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br>
    <br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br>
    <br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br><br><BR><br>
  
  

    <script  src="js/index.js"></script>




</body>

</html>

/*Downloaded from https://www.codeseek.co/adamjoiner/stickynav-on-scroll-fix-div-wzkgJb */
    #productMenuBar {
    border:1px solid #00ffff;

    text-align:center;

    z-index:9999;
    width:100%;
    max-width: 850px;
    margin: 0 auto; left:0px; right:0px;


    }

/*Downloaded from https://www.codeseek.co/adamjoiner/stickynav-on-scroll-fix-div-wzkgJb */
    var startProductBarPos=-1;
    window.onscroll=function(){
        var bar = document.getElementById('productMenuBar');
        if(startProductBarPos<0)startProductBarPos=findPosY(bar);

        if(pageYOffset>startProductBarPos){
            bar.style.position='fixed';
            bar.style.top=0;
        }else{
            bar.style.position='relative';
        }

    };


    function findPosY(obj) {
        var curtop = 0;
        if (typeof (obj.offsetParent) != 'undefined' && obj.offsetParent) {
            while (obj.offsetParent) {
                curtop += obj.offsetTop;
                obj = obj.offsetParent;
            }
            curtop += obj.offsetTop;
        }
        else if (obj.y)
            curtop += obj.y;
        return curtop;
    }

Comments