2

I've written the following jQuery plugin, which looks for all elements with the class "stretch", then identifies child elements with the class "stretch_this" and makes them all the height of the tallest "stretch_this" element within the parent.

$(document).ready(function () {
    stretchHeight()
});

$(window).resize(function () { 
    stretchHeight()}
);

function stretchHeight() {
    $('.stretch').each(function() {
        var maxHeight = -1;
        jQuery(this).find(".stretch_this").each(function() { //Resets the height so that it can work again on a resize.
            $(this).height('auto');
        });
        jQuery(this).find(".stretch_this").each(function() {
            maxHeight = maxHeight > $(this).height() ? maxHeight : $(this).height();
        });
        jQuery(this).find(".stretch_this").each(function() {
            $(this).height(maxHeight);
        });
        }
    )
}

It runs on the page load, and also whenever the page is resized as my overall layout is responsive and the height of the elements may change.

This works as expected, except when I refresh a page in Chrome, it reduces all image heights stretched in this way to 1px; this doesn't occur in IE. Loading the page afresh in Chrome (that is, hitting return in the address bar rather than hitting refresh) works fine - the elements resize as expected.

Why would this be? Is it an error in my code, or a quirk of Chrome? Is there any way around it. The plugin is deployed as part of a WordPress theme, if that matters.

Sinister Beard
  • 3,570
  • 12
  • 59
  • 95
  • one suggestion is instead of using three loops again and again on the same element you can put the three things in one loop. – Jai Oct 05 '15 at 08:38
  • 1
    Most probably, when you refresh, jQuery runs before the images have loaded. – lshettyl Oct 05 '15 at 09:18
  • @lshettyl - I was wondering if that might be the case, but why would it only happen on a refresh? – Sinister Beard Oct 05 '15 at 09:20
  • 1
    Because the DOM load could be quicker than the images. Even though the images are cached, they still needs to be drawn on the page. – lshettyl Oct 05 '15 at 09:23

1 Answers1

0

lshettyl suggsted that the issue may have been that the plugin was running before the images had loaded, because the DOM was loading quicker on a refresh; this was correct. So, using the using the advice here, I changed $(document).ready to $(window).load, and the plugin works fine.

Community
  • 1
  • 1
Sinister Beard
  • 3,570
  • 12
  • 59
  • 95