0

I am beginner and i am trying to display the width of the image. when i load for the first time it is giving correct width and if i reload it is displaying width as 0. Again when i try to load with chrome option "empty cache and hard reload" it is displaying correct width. Please unveil the mystery, i couldn't understand.

<html>
<head>
    <style type="text/css">
#latest_albums{

overflow: hidden;
margin: 1em 1em;
background-color: #009999;
}

.album li{
list-style-type: none;
float: left;
overflow: hidden;
margin: 2px 2px 0px 0px;
position: relative;


}

</style>

<script type="text/javascript" src="js/jquery-1.10.2.js"></script>

</head>
<body>
    <div id="latest_albums">

        <div class="album">
            <div class="set1">
            <li> <img src="albums/image1.jpg"> </li>
            <li> <img src="albums/image2.jpg"> </li>
            <li> <img src="albums/image3.jpg"> </li>
            <li> <img src="albums/image4.jpg"> </li>

            <li> <img src="albums/image5.jpg"> </li>
            <li> <img src="albums/image6.jpg"> </li>
</div>
<div class="set2">
            <li> <img src="albums/image1.jpg"> </li>
            <li> <img src="albums/image2.jpg"> </li>
            <li> <img src="albums/image3.jpg"> </li>
            <li> <img src="albums/image4.jpg"> </li>

            <li> <img src="albums/image5.jpg"> </li>
            <li> <img src="albums/image6.jpg"> </li>
</div>
        </div>

    </div>
    <script type="text/javascript">
var i=0,w = -150,SCROOL_WIDTH,WIN_WIDTH,IMG_MARGIN,IMG_WIDTH=10,TOT_ALBUMS,ALBUM_WIDTH;

IMG_WIDTH = $("div.album li").eq(0).width();

console.log(IMG_WIDTH);
</script>
</body>
</html>

thanks , ravi

2 Answers2

0

You should wait until the image is loaded before getting it's width (otherwise it wil return 0, because it doesn't know it's sizes). Try this:

$("div.album li:first img").load(function(){
    IMG_WIDTH = $("div.album li").eq(0).width();
    console.log(IMG_WIDTH);
});
Bobby
  • 292
  • 1
  • 12
0

Try like this:

<script type="text/javascript">
  $(document).ready(function() {
   var i=0,w = -150,SCROOL_WIDTH,WIN_WIDTH,IMG_MARGIN,IMG_WIDTH=10,TOT_ALBUMS,ALBUM_WIDTH;

   IMG_WIDTH = $("div.album li").eq(0).width();

   console.log(IMG_WIDTH);
});
</script>

There is also event handler image.onload that is executed when image is loaded. Sometimes even image.onload is not triggered so you can use timer to check when image width gets over 0. Check this: jQuery or Javascript check if image loaded

Community
  • 1
  • 1
Hardy
  • 5,590
  • 2
  • 18
  • 27