nunya
nunya

Reputation: 315

How would you change the height of a div based on the background image?

I am setting up pages to display the jpg's of comps that have been created and they all have a different height. Using javascript or jquery how would you auto adjust a div's height based on the height of the background image? The html would simply be laid out like so:

<body>
     <div id="comp"></div>
</body>

I realize you can set this is CSS but I want it to be dynamic and not have to add the height every single time. Thanks for any ideas at all.

Upvotes: 0

Views: 270

Answers (1)

jeffjenx
jeffjenx

Reputation: 17487

Perhaps this (untested) code will help you see how it can be done:

// taken from the link in my comment to OP
var url = $('body').css('background-image').replace('url(', '').replace(')', '').replace("'", '').replace('"', '');
var bgImg = $('<img />');
bgImg.hide();
bgImg.attr('src', url);
bgImg.bind('load', function()
{
    var height = $(this).height();
    $('#comp').height( height );
});

Upvotes: 1

Related Questions