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(); //hide image
  tempImg.bind('load', callback);
  $('body').append(tempImg); // add to DOM before </body>
  tempImg.attr('src', path);
  $('#tempImg').remove(); //remove from DOM
};

$(".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();Code language: JavaScript (javascript)

Posted

in

by

Tags:

Comments

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.