Ask your JavaScript questions! Pay money and get answers fast! (more info)

Dynamically set size of div JavaScript

  • SOLVED

I am working on a horizontal-scrolling website, and I need a solution to dynamically set the width of the div (because it has a repeating background) based on its contents.

This is the code I'm currently using - however this doesn't take into account the width of the images (of which there are a varying number of varying widths) because it occurs before the page has finished loading.

Any solutions/suggestions appreciated.

<script>
$(document).ready(function() {
var
$post = $(".section_post").outerWidth(true),
$comments = $(".section_comments").outerWidth(true),
$moreposts = $(".section_moreposts").outerWidth(true),
$images = 0; $('.section_images .image').each(function(){ $images = $images + $(this).outerWidth(true); }),
$total = $post + $images + $comments + $moreposts + 34;
$("#content_holder").width($total);
});
</script>

Answers (2)

2010-05-05

Andrzej answers:

hey, can you send me a link to website so I could have a closer look?


Andrzej comments:

Have you tried using $(document).load instead of $(document).ready ?

If it doesn't work, it might be worth to precise your content pictures widths in content editor? I'm assuming that content photos are inserted by Wordpress uploader? Then, they should have automatically added width and height html parameters i.e.
instead of
<img src="image.jpg">
do:
<img src="image.jpg" width="500" height="333">
etc.

If for some reason they don't do, you might want to set them up manully - this should fix the problem if first solution does not work here.


Dan Davies comments:

You = Genius
Me = Stupid.

Thanks ;)

2010-05-04

fuscata answers:

Try putting the script just before the body, without using $(document).ready:

<script>
$post = $(".section_post").outerWidth(true),
$comments = $(".section_comments").outerWidth(true),
$moreposts = $(".section_moreposts").outerWidth(true),
$images = 0; $('.section_images .image').each(function(){ $images = $images + $(this).outerWidth(true); }),
$total = $post + $images + $comments + $moreposts + 34;
$("#content_holder").width($total);
</script>
</body>


Dan Davies comments:

Alas that doesn't resolve it, I'm afraid :(