Search code examples
javascripthtmlcssvisible

keep div visible while scrolling only if second div is in view


I have the following (simplified) HTML code:

<div>
..stuff...
</div>
<div class="subtitle" id="charts-title">
    <h3>Charts for d/m/y</h3>
</div>
<div class="content" id="charts">
    ...various charts...
</div>
<div>
...more stuff...
</div>

So, #charts-title is not at the top of the page, nor #charts at the bottom, they are somewhere in the middle of the page. Now, when the user scrolls down, #charts-title goes out of the screen and then I'm seeing charts with no date information. I want to keep #charts-title visible only if #charts is in view.

Thanks for any help, Hector.


Solution

  • This made it:

    <div>
    ..stuff...
    </div>
    <div class="subtitle" id="float-charts-title" style="display:none; position:fixed; top: 0; z-index:100; background-color:white">
        <h3>Charts for d/m/y</h3>
    </div>
    <div class="subtitle" id="charts-title">
        <h3>Charts for d/m/y</h3>
    </div>
    <div class="content" id="charts">
        ...various charts...
    </div>
    <div>
    ...more stuff...
    </div>
    
    <script>
      $(window).scroll(function(){
      var rectTitle = $("#charts-title")[0].getBoundingClientRect();
      var rectCharts = $("#charts")[0].getBoundingClientRect();
      if (rectTitle.bottom < 0 && rectCharts.bottom > 0) {
        $("#float-charts-title").css("display", "block");
      } else {
        $("#float-charts-title").css("display", "none");
      }
    });
    </script>
    

    Thanks for the help.