0

Example: http://jsfiddle.net/forgetcolor/rZSCg/3/

Given a div set to overflow:auto, that will (likely) contain an image larger than its window, I'm trying to figure out a way to wait for that image to load before querying its properties. The property I'm after is it's inner width, minus its scrollbar. Thanks to a previous stackoverflow question (http://stackoverflow.com/questions/10692598/how-to-get-innerwidth-of-an-element-in-jquery-without-scrollbar) I've got a technique to do it, but this only works with a small tiny image, or one in the cache. When it gets a large image, the code that does the query executes before the image is done loading.

What I want is a way to wait for that image to load before doing the query. Any ideas?

Full example: http://jsfiddle.net/forgetcolor/rZSCg/3/

Javascript:

// using a random appended to the URL to simulate non-cached
// varying images
var r = Math.floor((Math.random()*100000)+1);
$('#box1').html("<img src='http://lorempixel.com/output/fashion-q-c-1920-1920-4.jpg?"+r+"' />");
var helperDiv = $('<div />');
$('#box1').append(helperDiv);
$('#iw').text("inner width is: " + helperDiv.width());
helperDiv.remove();
mix
  • 6,943
  • 15
  • 61
  • 90

2 Answers2

1

put everything you want to do in

$("img").load(function(){...});
L. Monty
  • 872
  • 9
  • 17
  • This will fail for cached images, and will not bind to the new image as it is not there for the append. – Fresheyeball May 22 '12 at 01:46
  • well...i did never use this function, I just know of the existence of it ...but ofcourse you can also make it to a live('load',function(){..}) if you want it to keep track on new-coming images... of course also the "img" selector will be to unspecific... I just wanted to give the function to use – L. Monty May 22 '12 at 01:53
  • This is true, but because this requires querying the dom, cached images will not fire a load event in IE and older FF. – Fresheyeball May 22 '12 at 01:54
1
   var r = Math.floor((Math.random()*100000)+1);
   var newImage = new Image()
   $(newImage).load(function(){
        $('#iw').text("inner width is: " + newImage.width);
   });
   newImage.src = 'http://lorempixel.com/output/fashion-q-c-1920-1920-4.jpg?'+r

The problem you are encountering is abit more complex. Images from the DOM have odd loading behaviors, where onload events do not always fire. So placing the image into a div then waiting for the DOM element to fire onload, is not going to work.

As a result we need the built in javascript image object. (recently learned) that this object will solve both your problems. First as long as you set your .load listener before you set the image source, it will fire onload every time in every browser. After the load has occurred, because its an image object, you don't need to add it to the page to get it's height and width, those properties are built in.

Fresheyeball
  • 29,567
  • 20
  • 102
  • 164