Using Dynamic Content's Image as Background Without Path in CSS

Description

Do you ever find yourself loading multiple pieces of dynamic content onto a page and need to use an image path from that content as a background image rather than an <img> element? You can't use the velocity variable in CSS because it won't compile, so what do you do?

The pseudo-code below uses javascript to grab multiple elements on a page, take the src attribute and set that to the CSS of the containing parent. My example will use <img> but you could simplify the code and use hidden input fields also.

(The reason we use <img> in our code is so the image still shows up even if the javascript is turned off)

Code

// Load on page load
jQuery(function() {
  // For each image/hidden field with the class .facility-image on the page
  jQuery(“.facility-image”).each(function() {
    // Grab the image and put it on the background
    var image_source = jQuery(this).attr('src');

    // Set the background – 
    // assumes the parent of the img is the element you want to set the background
    jQuery(this).parent().css("background-image",'url('+image_source+')');
                
    // Hide the original background image (not necessary if using hidden input fields)
    jQuery(this).hide();
  });
});