usagizmo
1/28/2018 - 8:40 AM

Align the last line element if justify-content is used

var FLEX_TARGET = '[data-align-last-row-elements]'
if ($(FLEX_TARGET).length) {
	var align = function() {
		$(FLEX_TARGET).each(function () {
			var group = [] // [maxColCount, maxColCount, ..., minColCount]
			var lastOffsetTop = null
			var tagName = null
			$(this).children().each(function () {
				if (!tagName) tagName = $(this)[0].tagName
				var offsetTop = $(this).offset().top
				if (lastOffsetTop === offsetTop) {
					group[group.length - 1] += 1
				} else {
					group.push(1)
				}
				lastOffsetTop = offsetTop
			})
			if (group.length >= 2) {
				var min = group[group.length - 1]
				var max = group[group.length - 2]
				var html = ''
				for (var i = min; i < max; i++) {
					html += '<' + tagName + '/>'
				}
				$(this).append(html)
			}
		})
	}
	$(window).on('resize', align)
	align()
}