Pushpin

Materialize is a modern responsive CSS framework based on Material Design by Google.

Pushpin is our fixed positioning plugin. Use this to pin elements to your page during specific scroll ranges. You can check out our live example: the fixed table of contents on the right.

Open Demo
Demo Code

// Pushpin Demo Init
const pushPinDemoNavElems = document.querySelectorAll('.pushpin-demo-nav');
pushPinDemoNavElems.forEach(navElem => {
  const navBox = navElem.getBoundingClientRect();    
  const contentElem = document.querySelector('#'+navElem.getAttribute('data-target'));
  const contentBox = contentElem.getBoundingClientRect();
  const offsetTop = Math.floor(contentBox.top + window.scrollY - document.documentElement.clientTop);
  M.Pushpin.init(navElem, {
    top: offsetTop,
    bottom: offsetTop + contentBox.height - navBox.height
  });
});


  // Only necessary for window height sized blocks.
  html, body {
    height: 100%;
  }
        

Initialization

Here is a sample initialization of pushpin. Take a look at what the options are and customize them to your needs.


  document.addEventListener('DOMContentLoaded', function() {
    var elems = document.querySelectorAll('.pushpin');
    var instances = M.Pushpin.init(elems, {
      // specify options here
    });
  });
        

Options

Name Type Default Description
top Number 0 The distance in pixels from the top of the page where the element becomes fixed.
bottom Number Infinity The distance in pixels from the top of the page where the elements stops being fixed.
offset Number 0 The offset from the top the element will be fixed at.
onPositionChange Function null Callback function called when pushpin position changes. You are provided with a position string.

Methods

All the methods are called on the plugin instance. You can get the plugin instance like this:


  var instance = M.Pushpin.getInstance(elem);
        
.destroy();

Destroy plugin instance and teardown


instance.destroy();
      

Properties

Name Type Description
el Element The DOM element the plugin was initialized with.
options Object The options the instance was initialized with.
originalOffset Number Original offsetTop of element.

CSS Classes

A pushpinned element has 3 states. One above and below the scrolling threshold, and the pinned state where the element becomes fixed. Because pushpin changes positioning, chances are your element will look different when the states change. Use these css classes to correctly style your 3 states.


  // Class for when element is above threshold
  .pin-top {
    position: relative;
  }

  // Class for when element is below threshold
  .pin-bottom {
    position: relative;
  }

  // Class for when element is pinned
  .pinned {
    position: fixed !important;
  }