Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

width returning 0 in jquery

i have some jquery script which runs after the window has loaded

$(window).load( function() {
   $('.picture a img').each(function(index) {
       $(this).height(280);
       if ($(this).width() > $(this).height()) {
          alert("yes");
       } else {
          alert("no");
       }

   });
});

i always get a "no" from this when i know some of the images should be a "yes". When i trace the script in chrome i noticed that the $(this).width() always returns a 0. ive googled around and some suggestions were that the images havent loaded but here ive used the window.load method which i thought should run once everything has loaded. any ideas??

thanks for any help in advance

like image 911
phil Avatar asked Jun 29 '11 15:06

phil


2 Answers

Chrome is weird about image widths. I noticed then when building a jQuery photo gallery. If your image width is not specifically set in the tag, chrome will return 0. FF, and IE will figure out the width, but chrome will not. Try actually setting the width and see if you get the desired result then.

<img width="200" src="..." />
like image 83
Cloudkiller Avatar answered Oct 18 '22 19:10

Cloudkiller


You need to run your code when the image is loaded, the following code should work:

$(window).load( function() {
   $('.picture a img').load( function() {
       $(this).height(280);
       if ($(this).width() > $(this).height()) {
          alert("yes");
       } else {
          alert("no");
       }
   });
}); 

note that every DOM element that have some kind of web resource associated to (window, img, iframe) respond to .load() event.

like image 35
Mo Valipour Avatar answered Oct 18 '22 21:10

Mo Valipour