abcid d
abcid d

Reputation: 2953

Set background image with jQuery

I am using <picture><source srcset> for image responsive. A requirement is images inside <picture> has to be set as background images.

I used jQuery to take image URLs and set them as background images. I then remove srcset so that they are not images anymore but become background images.

Problem: Somehow the url value doesn't show in 'url(myBG)' It shows <source media="(min-width: 768px)" style="background-image: url("myBG");"> in inspector. Please take a look at my JS and give me a hand.

Thanks

jsfiddle

JS

$('source').each(function() {
    var myBG = $(this).attr('srcset');
  console.log(myBG);
$(this).css('background-image', 'url(myBG)');
$(this).removeAttr('srcset');
})

HTML

<div>
<picture>
  <source media="(min-width: 768px)" srcset="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
  <source media="(min-width: 414px)" srcset="https://www.w3schools.com/tags/img_white_flower.jpg">
  <img src="https://www.w3schools.com/tags/img_pink_flowers.jpg">
</picture>
</div>

Upvotes: 0

Views: 86

Answers (1)

APAD1
APAD1

Reputation: 13666

It's because you're passing myBG in as a string. It should look like this: 'url('+myBG+')'

$('source').each(function() {
  var myBG = $(this).attr('srcset');
  console.log(myBG);
  $(this).css('background-image', 'url('+myBG+')');
  $(this).removeAttr('srcset');
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div>
  <picture>
  <source media="(min-width: 768px)" srcset="https://images.pexels.com/photos/414612/pexels-photo-414612.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500">
  <source media="(min-width: 414px)" srcset="https://www.w3schools.com/tags/img_white_flower.jpg">
  <img src="https://www.w3schools.com/tags/img_pink_flowers.jpg">
  </picture>
</div>

Upvotes: 1

Related Questions