Tuesday, February 21, 2012

Sticky floating headers inside of overflowing divs

In our latest project, we have some pretty sweet designs that have headers that drift down in the page as the user scrolls. But at some point the header will hit the end of the containing div and need to stop. (We have a date header for each transaction. The header stops floating once the next day's header is met in the scroll).

We had some luck using jquery plugin based on a good tutorial at Design Woop mixed with this updated Gist

But this fell apart when trying to use it with a div that had overflow set to 'auto' or 'scroll'. Since the plugin was calculating location based on document not the div element. Plus the plugin operated on single elements not on jquery objects.

CSS Looks like:
div.scroll {
        background-color: #eee;
        width: 600px;
        height: 200px;
        overflow:scroll;
      }

      .header {
        float: left;
        height: 30px;
        width: 600px;
        background-color: black;
        color: white;
        font-family: 'Times New Roman', serif;
        font-size: 20px;
      }

And html markup looks like (i've removed the extra text so it many not flow based on screen size and such).

html:
<div class="scroll">
  <div class="header" id="nowrapper">This is a header</div>
  <br class="clear">
   text here
  <div class="inside">
    <div class="header" id="lower">Lower Header</div>
    <br class="clear">
    more text here
  </div>
</div>

I couldn't find the plugin anywhere so I dumped it up in: https://github.com/lecar-red/jquery-stickyfloat and added support for floating inside a overflowed div.

To make that page work, after downloading updated stickfloat then add this javascript:
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7.1/jquery.min.js"></script>
<script type="text/javascript" src="js/jquery.stickyfloat.js"></script>
    <script type="text/javascript">
      $(function() { $(.header).stickyfloat({}) } );
    </script>

I'm hoping to put a tutorial but that will need to wait until another day. You can see how to use it in: https://github.com/lecar-red/jquery-stickyfloat/blob/master/overflow.html

__END__