Liam Liam - 1 year ago 42
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?

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




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


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

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