Liam Liam - 5 months ago 16
jQuery Question

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();

Answer

You put multiple jQuery-objects inside of "elem" because of using :last-child. According to jQuery documentation it may select more than one:

While :last matches only a single element, :last-child can match more than one: one for each parent.

So you should use :last instead.

Also i dont know what you mean by

!elem.prop('complete')

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

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