Search code examples
htmlcssscrollbarsearchbar

Display a Search bar on header on scroll HTML/CSS


I have a search bar which would like to display onto the header on scroll, a great example is like the one on this site: https://www.indiamart.com/


Solution

  • Approach 1 - A simple way to do this would be to detect a scroll & add and remove a class that contains display: none;

    You can have an event listener -

    window.addEventListener('scroll', function() {
       if( window.scrollY !== 0) {
                
          document.getElementById('searchBar').classList.add('scrolled');
       } else {
                
          document.getElementById('searchBar').classList.remove('scrolled');
       }
    });
    

    With the CSS -

    .noScroll
    {
        background: yellow;
        position:fixed;
        height: 50px; /*Whatever you want*/
        width: 100%; /*Whatever you want*/
        top:0;
        left:0;
        display:none;
    }
    
    /*Use this class when you want your content to be shown after some scroll*/
    .scrolled
    {
      display: block !important;
    }
    
    .parent {
      /* something to ensure that the parent container is scrollable */
      height: 200vh;
    }
    

    And the html would be -

    <div class="parent">
      <div class ='noScroll' id='searchBar'>Content you want to show on scroll</div>
    </div>
    

    Here's a JSFiddle of the same - https://jsfiddle.net/kecnrh3g/

    Approach 2 - Another simple approach would be

    <script>
    let prevScrollpos = window.pageYOffset;
    window.onscroll = function() {
    let currentScrollPos = window.pageYOffset;
      if (prevScrollpos > currentScrollPos) {
        document.getElementById('searchBar').style.top = '-50px';
      } else {
        document.getElementById('searchBar').style.top = '0';
      }
      prevScrollpos = currentScrollPos;
    }
    </script>
    

    with the html -

    <div class="parent">
      <div id ='searchBar'>Content you want to show on scroll</div>
    </div>
    

    and css

    #searchBar {
      background: yellow;
      position: fixed;
      top: 0;
      left: 0;
      height: 50px;
      width: 100%;
      display: block;
      transition: top 0.3s;
    }
    
    .parent {
      height: 200vh;
    }
    

    Here's a JSFiddle of the same - https://jsfiddle.net/0tkedcns/1/