Last active
December 30, 2015 08:59
-
-
Save willbroderick/7806634 to your computer and use it in GitHub Desktop.
Hide orphaned elements - the last unfull row of a grid, call on parent with child selector
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
//Ignore if you already have it: | |
$.fn.reverse = [].reverse; | |
//Hide orphaned thumbs, call on parent with child selector | |
$.fn.hideOrphans = function(selector, totalCountSelector){ | |
var selector = selector; | |
$(this).each(function(){ | |
var $children = $(this).find(selector); | |
$children.filter('.hidden-orphan').show().removeClass('hidden-orphan'); | |
if($(this).hasClass('show-orphans')) { | |
return true; | |
} | |
var lastRow = []; | |
var secondToLastRow = []; | |
var lastRowOffset = Math.floor($children.last().position().top); | |
var secondToLastRowOffset = -1; | |
$children.reverse().each(function(){ | |
var top = Math.floor($(this).position().top); | |
if(top == lastRowOffset) { | |
//Build last row | |
lastRow.push(this); | |
} else { | |
//Build second to last row | |
if(secondToLastRowOffset == -1) { | |
secondToLastRowOffset = top; | |
} | |
if(top == secondToLastRowOffset) { | |
secondToLastRow.push(this); | |
} else { | |
//Finally added last two rows | |
return false; | |
} | |
} | |
}); | |
//Any orphans to hide? | |
var hidden = 0; | |
if(secondToLastRow.length != 0 && secondToLastRow.length != lastRow.length) { | |
$(lastRow).addClass('hidden-orphan').hide(); | |
hidden = lastRow.length; | |
} | |
if(totalCountSelector) { | |
var t = $children.length - hidden; | |
$(this).find(totalCountSelector).html(t); | |
} | |
}); | |
return $(this); | |
}; | |
//Sample usage | |
$(window).on('debouncedresize hideorphans', function(){ | |
$('.product-list').hideOrphans('.product-block:not(.placeholder)', '.show-more .current-count'); | |
}).trigger('hideorphans'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment