2

I have a DIV with background-image. But my requirement is how can I extend the DIV size according to the height and width of background-image. I have tried some code with the help of this link.

var src = $('#divID').css('background-image').
                      replace('url', '')
                     .replace('(', '')
                     .replace(')', '')
                     .replace('"', '')
                     .replace('"', '');
$('body').append('<img id="appendedImg" src="' + src + '" style="height:0px;width:0px"');
var img = document.getElementById('appendedImg');       
var width = img.clientWidth;
var height = img.clientHeight; 
$('#appendedImg').detach();

I am just looking for any elegant solution if possible.

Community
  • 1
  • 1
Exception
  • 8,111
  • 22
  • 85
  • 136

2 Answers2

5

You probably just need to look for width/height onload:

var img = document.getElementById('appendedImg');
img.onload = function() {   
    var width = img.width;
    var height = img.height;
    console.log(width,height);
};

Also, you don’t need to attach it, creating a new image should be enough. Here’s how I would do it:

var $div = $('#divID'),
    src = $div.css('background-image').replace(/url\(\"([^\"]+).*/,'$1');

$(new Image).load(function() {
    $div.width(this.width).height(this.height);
}).attr('src', src);
David Hellsing
  • 106,495
  • 44
  • 176
  • 212
0

I would load the img first then get its height and width:

imgSrc = 'http://ajthomas.co.uk/wp-content/themes/ajthomascouk/library/images/logo.png'

// append the temp imag
$('body').append('<img src="'+imgSrc+'" alt="" style="display:none" id="dummyImage"/>');

// get the image width and height
imgWidth = $('#dummyImage').width()+'px';
imgHeight = $('#dummyImage').height()+'px';

// remove the image
$('#dummyImage').remove();

// set the css for the div
$('#imADiv').css({height: imgHeight, width: imgWidth, 'background-image': 'url('+imgSrc+')'});

Coded it up for you here - http://jsfiddle.net/LTdtM/

Alex
  • 8,875
  • 2
  • 27
  • 44