Return width 0 in jquery

I have some jquery script that 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 no from this when I know that some of the images should be yes. When I trace the script in chrome, I noticed that $(this).width() always returns 0. ive googled around, and some suggestions were that the images were not loaded, but here ive used the window.load method, which I thought it should start as soon as everything is loaded. any ideas?

thanks for any help in advance

+7
source share
6 answers

Chrome is weird regarding the width of the image. Then I noticed that when creating jQuery photo galleries. If your image width is not specifically set in the tag, chrome will return 0. FF, and IE will determine the width, but chrome will not. Try setting the width and see if you get the desired result.

 <img width="200" src="..." /> 
+1
source

You need to run the code when loading the image, 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 each DOM element that has some web resource associated with (window, img, iframe) responds to a .load () event.

+1
source

to try

if ($(this).attr("width") > $(this).attr("height")) {

0
source

try adding a upload event to the image, so it will only run when the image is fully loaded.

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

you can also check this.complete on the image object

0
source

I just wanted to add that you also need to make sure that your image is actually a visible element. In the past, I had a lot of problems trying to measure visibility: hidden or visible: no elements. If you are really trying to measure a hidden element, you can go past it by doing something like

 var width = $('img').show().width(); $('img').hide(); 

Now this code is incredibly vague, but it gives you an idea of ​​blinking visibility.

0
source

The correct way to use it to run your scripts after the dom download is complete is as follows:

 $(document).ready(function() { /*your code here*/ }); 
-5
source

All Articles