JohnTaa
JohnTaa

Reputation: 2824

impossible to retrieve the image width if the css attribute is not set

On all browsers but firefox , It seems impossible to retrieve the image width if the css attribute is not set, I tried all the codes that I found but cannot solve this Issue, Here is the Html code

<div class="slide"><img src="../images/image1.jpg"/></div>
<div class="slide"><img src="../images/image2.jpg"/></div>
<div class="slide"><img src="../images/image3.jpg"/></div>

and Javascript

    var slideWidth = parseInt($('.slide').find('img:first').css('width'));
    alert(slideWidth);      //Works on FF but not Other browsers 
    var slideWidth = $('.slide').children('div > img:first').width();
    alert(slideWidth);        //Works on FF but not Other browsers 

the alert will show you the right width on FF but will show 0 on others Is there any way to solve this problem , Thank you..

Here an Example :

http://jsfiddle.net/j82s6/

Upvotes: 0

Views: 92

Answers (2)

Miljan Puzović
Miljan Puzović

Reputation: 5820

Your code works fine if you select onLoad option in jsfiddle (I'm using Chrome).

http://jsfiddle.net/j82s6/4/

Make sure that you put your code inside this

$(document).ready(function{
  // your code
});

Upvotes: 0

Kevin Pei
Kevin Pei

Reputation: 5872

You forgot to wait for the image to load first - other browsers are retrieving the width before the image loaded. Use the .load() event.

Fiddle: http://jsfiddle.net/M6TxJ/
JS:

$('.slide img:first').load(function(){
    var slideWidth = parseInt($('.slide').find('img:first').css('width'));
    alert(slideWidth);      //Works on FF but not Other browsers 
    var slideWidth = $('.slide').children('div > img:first').width();
    alert(slideWidth);

});

Upvotes: 1

Related Questions