JSFiddle - React, Tailwind, and code Playground

by Santosh Thakur

HTML

<div class="header" id="header">
  header
</div>

<div class="middle" id="middle">
  <div class="content" id="myP">this is content</div>
</div>

<div class="footer" id="footer">
  Footer
</div>

CSS

body {
   background: #ffcc00;
   height: 100%;
 }

 .middle {
   border: 2px solid red;
   overflow: hidden;
   height: 1000px;
   position: relative;
 }

 .content {
   width: 450px;
   height: 200px;
   background: #fff;
 }

 .content.fix {
   position: fixed;
   top: 0px;
   background: red;
 }

 .content.abs {
   position: absolute;
   bottom: 0px;
   background: green;
 }

 .header {
   height: 1000px;
   background: #666;
 }

 .footer {
   height: 1000px;
   background: #ccc;
 }

JavaScript

window.onscroll = function() {
    myFunction();
  };



  // console.log("Header >>>> ", head.clientHeight );
  // console.log("Footer >>>> ", footer.clientHeight );


  function myFunction() {
    // document.documentElement.scrollTop > 50
    var scroll = document.body.scrollTop + document.documentElement.scrollTop;

    var head = document.getElementById('header');
    var footer = document.getElementById('footer');
    var middle = document.getElementById('middle');

    console.log(">>>>>>>>>>>>>>>>>> (1) ", scroll);
    console.log(">>>>>>>>>>>>>>>>>> (2) ", middle.clientHeight + footer.clientHeight);
    console.error(">>>>>>>>>>>>>>>>>> (3) ", scroll >= middle.clientHeight + footer.clientHeight);

    if (document.body.scrollTop > head.clientHeight || scroll >= head.clientHeight) {

      document.getElementById("myP").classList.add("fix");
      document.getElementById("myP").classList.remove("abs");

    } else if (document.body.scrollTop > middle.clientHeight + footer.clientHeight || scroll >= middle.clientHeight + footer.clientHeight) {

      // debugger;
      document.getElementById("myP").classList.remove("fix");
      document.getElementById("myP").classList.add("abs");

    } else {

      document.getElementById("myP").classList.remove("abs");
      document.getElementById("myP").classList.remove("fix");

    }

  }