1

I have some code which basically puts an image description next to an image of unknown height. Some pseudo code here:

$( document ).ready(function() {
  $(".productdescription").css({'height':($(".productimage img").height()+'px')});
});

See it in action here: http://jsfiddle.net/94xn5/

This code works on jsfiddle but in my real code it re-sizes the div about 1/2 of the time correctly and about 1/2 of the time it resizes to 0px....

I'm having trouble debugging why it works sometimes and others not?

If it helps - I'm testing this inside a shopify preview pane, perhaps this is screwing with my JS somehow?

Thanks!

PS - if there's an easier way to do what I'm trying to do with just pure CSS please let me know! I'm not experienced with either JS or CSS

Edit - this sounds weird but if I hit cmd+r to refresh the page the box stays 0px styled but if I click in the address bar and hit return it correctly sizes the box. Not sure what that means but helps narrow down when it works and when it doesn't?!

tomcritchlow
  • 785
  • 2
  • 11
  • 28

2 Answers2

4

Change $(document).ready(...) event to $(window).load(...) event and it should work.

Your pictures are probably not ready (not fully loaded) when JS "attacks".

.load() event is triggered after all resources are fetched.

veritas
  • 2,034
  • 1
  • 16
  • 30
  • This works! Thanks so much - I thought document.ready waited for resources to load but now I understand the difference :) perfect. thanks so much. – tomcritchlow Jan 19 '14 at 16:44
1

it is because the image might not be loaded, wait from image load

$(document).ready(function () {
    $(".productimage img").load(function () {
        $(".productdescription").height(this.height)
    }).filter(function () {
        //if the image is already loaded trigger the event manually
        return this.complete;
    }).trigger('load');
});
Arun P Johny
  • 384,651
  • 66
  • 527
  • 531