Copy <img> src attribute and set it as a background image

Viewed 461

I'm trying to customise the way portfolio is being displayed on my website. Instead of featured image being displayed as an image I would like it to display as a div's background-image. So want I want to do is to copy src attribute and set as css background-image of its parent and like that to each work-item displayed.

Here is the HTML structure that I'm working with and the jQuery code I've used

<div class="caroufredsel_wrapper">
   <ul class="portfolio-items">
      <li>
        <div class="work-item">
           <img class="custom-thumbnail" src="../wp-content/Project.jpg">
        </div>
      </li>
      <li>
        <div class="work-item">
           <img class="custom-thumbnail" src="../wp-content/Project2.jpg">
        </div>
      </li>
   </ul>
</div>


<script type="text/javascript">
    (function($) {
        $(document).ready(function() {
            $(".work-item").find("img").each(function(n, image){
                var image = $(image);
                var thisUrl = $(this).attr("src");
                image.parents(".work-item").css("background-image", "url(' + thisUrl + ')");
            });
        });
    }(jQuery));
</script>

But instead of a link being set as a background-image this is the output I get

<div class="work-item" style="background-image: url('+ thisUrl +');">
     <img class="custom-thumbnail" src="../wp-content/Project.jpg">
</div>
2 Answers

you need to replace url(' + thisUrl + ') with url(" + thisUrl + ")

<script type="text/javascript">
    (function($) {
        $(document).ready(function() {
            $(".work-item").find("img").each(function(n, image){
                var image = $(image);
                var thisUrl = $(this).attr("src");
                image.parents(".work-item").css("background-image", "url(" + thisUrl + ")");
            });
        });
    }(jQuery));
</script>

Just another thing that's just as easy to do without jQuery (I find it even easier):

document.addEventListener('DOMContentLoaded', () => {
  for (const img of document.querySelectorAll('.work-item img')) {
    img.parentElement.style.backgroundImage = `url(${img.src})`;
  }
})
<div class="caroufredsel_wrapper">
   <ul class="portfolio-items">
      <li>
        <div class="work-item">
           <img class="custom-thumbnail" src="../wp-content/Project.jpg">
        </div>
      </li>
      <li>
        <div class="work-item">
           <img class="custom-thumbnail" src="../wp-content/Project2.jpg">
        </div>
      </li>
   </ul>
</div>

Related