Skip to content

Instantly share code, notes, and snippets.

@wilfreddenton
Last active August 29, 2015 14:26
Show Gist options
  • Save wilfreddenton/5e0f845070f1666f29d2 to your computer and use it in GitHub Desktop.
Save wilfreddenton/5e0f845070f1666f29d2 to your computer and use it in GitHub Desktop.
/**
* This module will stack items on your page. Use it by
* var stacker = require('stacker'); stacker(params);
*
* @param {string} klassString the class of the items to target
* @param {number} columns the number of columns in your rows
* @param {number} breakpoint the width at which this module should disable itself
*/
var _stacked = true
, _klass = ''
, _cols = 0
, _brkpnt = 0
, _items = [];
function _unstack() {
for (var i = _cols; i < _items.length; i += 1) {
_items[i].style.marginTop = '0px';
}
stacked = false;
}
function _stack() {
for (var i = _cols; i < _items.length; i += 1) {
var item = _items[i];
var itemAbove = _items[i - _cols];
var itemRect = item.getBoundingClientRect();
var itemAboveRect = itemAbove.getBoundingClientRect();
var height = itemAboveRect.top + itemAboveRect.height;
var difference = height - itemRect.top + Number(item.style.marginTop.slice(0, -2));
if (difference != 0) {
item.style.marginTop = difference.toString() + 'px';
}
}
_stacked = true;
}
function _init() {
if (window.innerWidth <= _brkpnt) {
_stacked = false;
} else {
_stack();
}
window.addEventListener('resize', function(e) {
if (_stacked) _unstack();
if (window.innerWidth > _brkpnt) {
_stack();
}
});
}
function stacker(klassString, columns, breakpoint) {
_klass = klassString;
_cols = columns;
_brkpnt = breakpoint;
_items = document.querySelectorAll('.' + klassString);
_init();
}
module.exports = stacker;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment