André Amorim

Crafting Web Experiences

//

Background image sized row/div

If you want to determine a section height by it’s background image to fit it correctly, use the jQuery code below and put “.bg-sized” class into the section:

$.fn.getBgImage = function(callback) {
  var height = 0;
  var path = "";
  if ( $(this).css('background-image') ) path = $(this).css('background-image').replace('url', '').replace('(', '').replace(')', '').replace('"', '').replace('"', '').replace("'", '').replace("'", '');
  var tempImg = $('<img />');
  tempImg.hide(); 
  tempImg.bind('load', callback);
  $('body').append(tempImg); 
  tempImg.attr('src', path);
  $('#tempImg').remove(); 
};

$(".bg-sized").each(function() {
  var row_to_size = $(this);
  row_to_size.getBgImage(function() {
    var this_bg = $(this);
      $(window).on("resize", function () {
        var target_width = $('body').width();
        var scale = this_bg.height() / this_bg.width();
        row_to_size.css('height', target_width * scale);
      }).resize();
    });
}).resize();

Published date:

Modified date: