Sticky

Stick elements to the top of the viewport or directly below a sticky nav. Mainly used for sticking nav bars to the top of the viewport.


Initializing

The demo pages already include the following code. These steps are only necessary if you are building a page from scratch. Remove these references if you are not using this plugin to improve page load times.

mrSticky relies on the ScrollMonitor plugin.

  1. Include the library in your page
    • Copy the script tag below and paste in the foot of your page. Add this where you see the other library scripts. This line should be inserted after jquery.js and before theme.js.

      <!-- ScrollMonitor (manages events for elements scrolling in and out of view) -->
      <script type="text/javascript" src="assets/js/scrollMonitor.js"></script>

      Alternatively you may wish to load this resource from a CDN to potentially improve page load times.

      <!-- ScrollMonitor (manages events for elements scrolling in and out of view) -->
      <script type="text/javascript" src="https://unpkg.com/scrollmonitor@~1.2.4"></script>
  2. Load the initializer code in index.js
    • Declare the following import statement in js/mrare/index.js. This ensures that the initializer code is included in the theme.js bundle.

      import mrSticky from './sticky';
    • Ensure the following line appears in the export object:

      export {
      mrSticky,
      };

Basic Usage

Elements such as <nav>s can stick to viewport top with the addition of the data-sticky="top" attribute.

To stick a <nav> to the top of the window, it must be wrapped in a div.navbar-container.

<div class="navbar-container">
  <nav class="navbar" data-sticky="top">
    ...
  </nav>
</div>

To make other elements sticky, add data-sticky="below-nav". The element will then scroll with the page, and stick below the main nav. If the sticky element has a <section> ancestor the element will un-stick and scroll out of view with the ancestor.

See Also: This functionality works well with our Overlay Nav plugin.