EvanLovely
7/29/2015 - 5:28 PM

Turn img tags to background images

Turn img tags to background images

$('.js-bg-to-img').each(function () {
  $(this).find('img').each(function () {
    var $img = $(this);
    var src = '';
    var $wrapMe;

    src = $img.attr('src');
    $wrapMe = $img;
    if (src.length) {
      // we have a value

      if ($wrapMe.parent().hasClass('bg-img') === false) {
        // first run
        $wrapMe
          .addClass('hide')
          .wrap('<div></div>')
          .parent()
          .attr('style', 'background-image: url(' + src + ');')
          .addClass('bg-img bg-img--expand');
      }

    } else {
      // error; no `src` found
      console.error("img src wasn't found, so it wasn't turned into a background image.", $img);
    }
  });
});