Petr Kann
Petr Kann

Reputation: 49

Loading image in background not applying CSS styles

Can you help me? I'm using a script to set the image when it has loaded but the style is not being applied together.

$('img[data-src]').each(function() {
   var img = $(this);
   var newimg = new Image();
   newimg.src = img.attr('data-src');
   newimg.setAttribute('class', img.attr('data-src'));
   newimg.onload = function() {
   img.replaceWith(newimg);
   };
});

I can't put here the HTML & CSS styles because every < img > tag has custom style, so I need make this script above works to inherit styles.

What should I do to solve this issue? Thanks

Upvotes: 0

Views: 36

Answers (1)

Mark E
Mark E

Reputation: 3483

That's because you are creating a new element which does not have the same class and style attributes. Just copy them to the new element.

$('img[data-src]').each(function() {
   var img = $(this);
   var newimg = new Image();
   newimg.src = img.attr('data-src');
   newimg.setAttribute('class', img.attr('class'));
   newimg.setAttribute('style', img.attr('style'));
   newimg.onload = function() {
   img.replaceWith(newimg);
   };
});

Upvotes: 1

Related Questions