views:

61

answers:

1

I have a code that would call $.load() to get an HTML fragment. In the fragment there will be a list of images and a script that would do some calculation based on the list size. The fragment looks like

<div>
  <ul>
    <li><img .../></li>
    <li><img .../></li>
    ...
  </ul>
</div>

<script>
   //... script to do calculation on the list width
</script>       

Originally, I use css's max-width to ensure that the image would not exceed 180px. But as IE has no max-width, I use the expression hack. However, it seems when the image are first load, the script cannot get a correct width of image list. Seems like the script load earlier than the CSS expression.

If it is a new page, I can certainly call $(window).load() to ensure all the images are loaded. But what can I do in an ajax html fragment request?

+1  A: 

DEMO: http://jsbin.com/ehawa/2

Javascript method is for offsetWidth

es: document.getElementById("UL_ID").offsetWidth

EXAMPLE WORKING CODE with jQuery:

       <style>
        ul { list-style:none; margin:0; padding:0 }
        ul li { margin:10px }
        ul li img { /* width:180px */ }
        div { float:left; width:200px; background:#333 }
        </style>

      <script>
    $(function() {

        setImgWidth();

    });

// then Insert the same function After the Ajax Call

 function setImgWidth() {

    $('ul li > img').each(function() {
        //get it's width
        var img = $(this).width();
        if (img > 180) {
            $(this).attr('style', 'width:180px');
        }
    });

}
        </script>


    <div>
      <ul>
        <li><img src="http://l.yimg.com/g/images/home_photo_junku.jpg" alt=""/></li>
        <li><img src="http://l.yimg.com/g/images/home_photo_tarotastic.jpg" alt=""/></li>
      </ul>
    </div>

hope this help!

aSeptik
No. Actually I'm calculating the width of ul where the lis inside are floated left. The li contains image with css max-width properties. But since IE has no max-width, I have to use expression: this.width<180? this.width:180; The problem seems that the expression for a fresh image is evaluated after the script so the width calculated is not always correct.
jackysee
in a ajax scenario you just need to put the jquery call above inside a function and call it after the ajax request it should work as expected! Let me know!
aSeptik