Liam
Liam

Reputation: 9855

When images loaded change background, jQuery

I'm trying to write a function that once the last image in an element is loaded it sets it as the parents background image only I cant seem to get it working...

I can alert the source but for some reason not affect the parent with no console errors?

https://jsfiddle.net/09ss43nx/1/

function swapImage(){

var elem = $('.team-member img:last-child');
if (!elem.prop('complete')) {
  console.log("Waiting to be loaded!");
  elem.on('load', function() {
    elem.parent().css('background-image', elem.attr('src'));
  });
} else {
  elem.parent().css('background-image', elem.attr('src'));
}

}

swapImage();

Upvotes: 0

Views: 99

Answers (1)

Mick
Mick

Reputation: 8913

You dont have any loop so far. Also i dont know what you mean by

!elem.prop('complete')

If you want to loop trough all images and check if they are loaded, that is what you need:

function swapImage(){
  var parents = $('.team-member');

  parents.each(function(i) {
    var images = $(this).find('img');

    images.each(function(i) {
        $(this).load(function() {
            console.log('loaded image!');
        });
    })
  });
}

swapImage();

But we don't get the console.log "loaded image!". This is probably because the images are already loaded before this function kicks in. Also the onload works asynchronous so the $.each-loop would continue. You could set a global variable and write the image into it instead of the console.log . Then you know which one was loaded last, but since its asynchronous, you need to call another function which checks if all images are loaded.

Anyway you also missed to set correct css-style background-image: url('...'):

elem.parent().css('background-image', 'url('+elem.attr('src')+')');

Upvotes: 1

Related Questions