Search code examples
jqueryimageheightequalspageload

jquery images with equal height


I am trying to write a Jquery function which will match the heights of all images on a page with the same class name.

This works as expected providing the internet connection is decent. If the images take a while to load, then it fails to display any images. I assume the function is determining the image to be 0px height and setting this to all.

How can I get around this?

Many thanks

function equalizeClass(className) {
    var equaliserHeight = 0;
    var height = 0;
    var i = 0;
    $('.'+className).each(function() {
        $(this).imagesLoaded(function() {
            i++;
            height = $(this).height();
            if(height>equaliserHeight) {
                equaliserHeight = height;
            }   
        });
    });
    $('.'+className).css("height", equaliserHeight);
}

$(function() {
equalizeClass('products-page-product-img'); // Equalize product list thumbnails
});

Solution

  • Just wait to page load. Replace:

    $(function() {
      equalizeClass('products-page-product-img');
    });
    

    with:

    $(window).load(function() {
      equalizeClass('products-page-product-img');
    });