JSFiddle - React, Tailwind, and code Playground

by _sir

HTML

<div id="gnbWrap">
  <div class="fixedTop">
  
  </div>
  <div id="gnb">
 
  </div>
</div>
<div class="foo">
  A Thing
</div>
<div class="foo">
  A Thing
</div>
<div class="foo">
  A Thing
</div>
<div class="foo">
  A Thing
</div>
<div class="foo">
  A Thing
</div>
<div class="foo">
  A Thing
</div>

CSS

body {
  margin: 0;
  padding: 0;
}

.foo { 
  height: 150px; 
  margin: 1em; 
  padding: 1em;
  background: rgba(200,200,200,.2);
}

.fixedTop {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
}

.banner1, .banner2 {
  height: 28px; 
  background: red; 
  color: white; 
  text-align: center;
  min-width: 90%;
}

.banner2 {
  background: blue;
}

.fixedOnly { 
  visibility: hidden;
}

.fixedTop .fixedOnly {
  visibility: visible;
}

JavaScript

function addContent(contentHTML){
  var $win = $(window);
  var $gnbWrap = $('#gnbWrap');
  
  // Containers for the content
  var $gnb = $('#gnb');
	var $top = $('.fixedTop');

  // Get the current GNB height
  var origHeight = $gnb.height();
    
  // Put the div on the page so it gets all the correct CSS
  $gnb.append(contentHTML);
  
  // Get the height of important things
  var newHeight = $gnb.height();
  
  // Figure out where the window is and where it needs to be.
  var currTop = $win.scrollTop();
  var newTop = currTop + (newHeight - origHeight);
  
  // alert([currTop, newHeight, origHeight, newTop].join(' '));
  
  // Add a content clone to the fixed top zone
  $top.append($gnb);

  // Make space
  $gnbWrap.height(newHeight);
  
  // Set scrollTop
  $win.scrollTop(newTop);
  
  // Delete the clone if we reach the top
  $win.on('scroll.gnb', function(){
    if ($win.scrollTop() === 0) {
      $win.off('scroll.gnb');
      
      // Move the GNB into the flow
      $gnb.appendTo($gnbWrap);
    }
  })
}

setTimeout(function(){
  addContent('<div class="banner1">Something <span class="fixedOnly">(Fixed)</span></div>');
}, 2000);
setTimeout(function(){
  addContent('<div class="banner2">Something <span class="fixedOnly">(Fixed)</span></div>');
}, 4000);