Instantly share code, notes, and snippets.
SebastianHonert/align-add-to-cart-buttons.js
Last active Jan 31, 2018
WooCommerce/Storefront align add-to-cart buttons
/** | |
I prefer this solution to setting a CSS min-height for the product list | |
items because the height of the items might vary significantly, resulting | |
in rows with too much space between order button and the list item content. | |
*/ | |
// Wait until images are loaded to get correct list item height | |
jQuery(window).load(function() { | |
var $ = jQuery; | |
// Default mobile breakpoint | |
function isMobile() { | |
return $(window).innerWidth() < 768; | |
} | |
// Extend jQuery | |
$.fn.changeCartButtonCSS = function(setCount) { | |
if( isMobile() ) { | |
$('.add-to-cart-button-wrapper').css('padding-top', '0'); | |
return; | |
} | |
for(var i = 0; i < this.length; i+=setCount) { | |
var currentSet = this.slice(i, i+setCount); | |
var elementHeights = currentSet.map(function() { | |
var elPaddingTop = parseInt( $(this).children('.add-to-cart-button-wrapper').css('padding-top') ); | |
return $(this).innerHeight() - elPaddingTop; | |
}).get(); | |
var maxHeight = Math.max.apply(null, elementHeights); | |
currentSet.each(function() { | |
$(this).children('.add-to-cart-button-wrapper').css('padding-top', '0'); | |
var diff = jQuery(this).innerHeight() - maxHeight; | |
$(this).children('.add-to-cart-button-wrapper').css('padding-top', -diff + 'px'); | |
}); | |
} | |
return this; | |
}; | |
function resizeProductListElements() { | |
var ul = $('ul.products'); | |
$.each(ul, function() { | |
var li = $(this).find('li.product'); | |
var length = 1; | |
$.each(li, function() { | |
if( $(this).hasClass('last') ) { | |
return false; | |
} else { | |
length++; | |
} | |
}); | |
li.changeCartButtonCSS(length); | |
}); | |
} | |
// Wrap each button in a div for CSS styling | |
$('a.add_to_cart_button').wrap('<div class="add-to-cart-button-wrapper"></div>'); | |
// Resize list items on page load | |
resizeProductListElements(); | |
// Resize list items on window resize | |
$(window).on('resize', function() { | |
resizeProductListElements(); | |
}); | |
}); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment