How to set DIV sizes by height and width of background image

I have a div with a background image. But my requirement is how to increase the size of the DIV according to the height and width of the background image. I tried the code using 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.

+2
source share
2 answers

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

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

In addition, you do not need to attach it, creating a new image should be enough. Here's how I 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); 
+5
source

I would load 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+')'}); 

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

0
source

All Articles