Last active
August 29, 2015 14:05
-
-
Save wilfreddenton/86208cfcbc3cd53c0153 to your computer and use it in GitHub Desktop.
Stacker
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
(function($) { | |
/** | |
* This module will stack items on your page. Use it by calling | |
* stacker(params) in the global namespace. Stacker requires jQuery. | |
* | |
* @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, | |
items = []; | |
this.stacker = function(klassString, columns, breakpoint) { | |
klass = klassString; | |
cols = columns; | |
items = $('.' + klass); | |
if ($(window).width() <= breakpoint) { | |
stacked = false; | |
} else { | |
stack(); | |
} | |
$(window).resize(function() { | |
if ($(this).width() <= breakpoint) { | |
if (stacked) { | |
unstack(); | |
} | |
} else { | |
stack(); | |
} | |
}); | |
}; | |
function unstack() { | |
// loop through items and reset their top margin | |
for (var i = cols; i < items.length; i += 1) { | |
$(items[i]).css({marginTop: '0px'}); | |
} | |
// set stacked to false | |
stacked = false; | |
} | |
function stack() { | |
// loop through items and set and individual item's top margin | |
// to minus the space between it and the item above it. | |
for (var i = cols; i < items.length; i += 1) { | |
var $item = $(items[i]), | |
$itemAbove = $(items[i - cols]); | |
// get the combined height of the above item's distance from the top and height | |
var height = $itemAbove.offset().top + $itemAbove.height(); | |
// subtract the item's distance from the top and its top margin from the height calculated above | |
// the answer will be 0 or negative | |
var difference = height - $item.offset().top + Number($item.css('margin-top').slice(0, -2)); | |
if (difference != 0) { | |
$item.css({marginTop: difference + 'px'}); | |
} | |
} | |
// set stacked to true | |
stacked = true; | |
} | |
})(jQuery); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment