0

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.

Captain Obvlious
  • 19,754
  • 5
  • 44
  • 74
nunya
  • 305
  • 1
  • 5
  • 17
  • 1
    I think its not possible to find the background image height or width using jquery – thecodeparadox May 23 '12 at 17:54
  • 1
    Here is a potential way of getting the background image height: http://stackoverflow.com/a/5106301/1028949 – jeffjenx May 23 '12 at 17:55
  • Is the div a child of the background image? – neuDev33 May 23 '12 at 17:55
  • I have done some research. There are ways to find the height/width of an image but nothing about taking those dimensions and auto adjusting a div's height. – nunya May 23 '12 at 17:56
  • MrSlayer - I did check that out but after determining the size how would you "attach" those dimension to the div sizes? – nunya May 23 '12 at 17:59

1 Answers1

1

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 );
});
jeffjenx
  • 17,041
  • 6
  • 57
  • 99
  • I tried out this suggestion but it's returning this error "ReferenceError: Can't find variable: $" – nunya May 23 '12 at 18:13
  • [Look around](http://stackoverflow.com/questions/4888725/jquery-referenceerror-cant-find-variable) for answers to help you understand why that error is coming up – jeffjenx May 23 '12 at 18:24