views:

226

answers:

3

I'm trying to use jQuery to find the image height of the first "grand children" of a container, then set the container to that height. But, I can't seem to pull the image height attribute - getting the src works. Any ideas? Is it just trying to pull the heights via CSS? How do i get the "real heights" I can't input the width and height in img tag - so that's not an option ;(

 $(document).ready(function() {
       var imageContainer = '#image-container';


       var imageSrc = $(imageContainer).children(':first').children(':first').attr('src'); // control test
       var imageHeight = $(imageContainer).children(':first').children(':first').height(); // have also tried attr('height')

       alert(imageSrc + ' ' + imageHeight);

    });


    <div id="image-gallery">
      <div id="image-container">    

        <div class="slide">
          <img src="test1.jpg" alt="test1" />
          <p>
            <strong>This is a test 1</strong>
          </p>
        </div>

        <div class="slide">
         <img src="test2.jpg" alt="test2" />
         <p>
           <strong>This is a test 2</strong>
         </p>
       </div>

      </div>
    </div>
+1  A: 

From the API docs:

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.

So instead of executing your script in $(document).ready(); use $(window).load(); or better yet, $(image).load();. For example:

$(document).ready(function() {
    var imageContainer = '#image-container';

    $(imageContainer).children(':first').children(':first').load(function() {
        var imageSrc = $(this).attr('src'); // control test
        var imageHeight = $(this).height(); // have also tried attr('height')

        alert(imageSrc + ' ' + imageHeight);
    });
});
Joel Potter
+1  A: 

The reason that you can't get the size of the images is that they don't have any size yet. The code runs after the page has loaded but before the images has loaded.

Run the part of the code that needs the image size after all elements in the page are loaded:

$(window).load(function () {
  ...
});
Guffa
+1  A: 

you should wait until your image is loaded - something along the line of

 $('#imageContainer').children(':first').children(':first').load(function() {
     alert($(this).height());
 });
roman