0

Here is a little sample: http://cdpn.io/Gpdyx

It contains a PictireFill script from:

https://github.com/scottjehl/picturefill

and small jQuery code that tries to set same height of .copy element as the image height.

The problem is when PictureFill comes into a play - image is obviously not loaded when jQuery fires document ready script - so it can't set correct .copy height. But when you resize the browser - everything works fine as the image is already there.

How could I detect an action when the image is loaded by PictureFill and fire my resizeAction function so everything works smoothly as it should?

Ps. The codepen is simplified to the maximum. PicruteFill might have multiple images as an arguments (different sizes for different browser widths etc), and there might be multiple sections working as the example - so the solution should be universal.

Edit2: As suggested I have used imagesLoaded - and it almost works... except on firefox on the first time image is loaded it doesn't fire correctly. On Chrome everything works fine. Any suggestions?

Marcin Bobowski
  • 1,745
  • 2
  • 19
  • 35

2 Answers2

1

Try something along these lines:

var imgArray = {pic1url,pic2url...};
var i = 0;
function loadImage(picsrc) {
    var pic = new Image()
    pic.onload = function() {
        if (i >= imgArray.length) {
             your_resize_function();  // finished loading and do resize
        } else {
             loadImage(imgArray[i]); // load next image
        };
        i++;
    };
    pic.src = picsrc;
}

You have to specify the source after the onload bit. Then as soon as the browser has finished downloading the image it'll run the function you need.

Taintedmedialtd
  • 856
  • 5
  • 13
  • It might work, yet I need more universal method, specially because with PictureFill there are more than 1 possible images, and I can have multiple elements on a page that should behave this way – Marcin Bobowski Mar 28 '14 at 10:39
1

an alternative to Tantedmedialtd's answer would be to implement a jQuery library like ImagesLoaded https://github.com/desandro/imagesloaded

this will fire events when each/all/some images finish loading and allows for both transitioning in of the individual images as well as firing events off to external listeners

haxxxton
  • 6,422
  • 3
  • 27
  • 57