views:

68

answers:

2

I have an <img> and some <p>'s inside a <div>.

I want to get the width of the child img and apply it to the width of the parent div so that the paragraphs of text will wrap to the same width as the img.

I want to be able to do this to multiple iterations on the same page.

Background: I am developing a wordPress theme that uses the masonry jquery plugin (http://desandro.com/resources/jquery-masonry). My theme has something in common with Gridalicious theme (http://suprb.com/apps/gridalicious) but the post widths and sizes will be dictated by the image width and will not be uniform.

My html/css is spotless but my jquery / javascript is pretty shaky - but if I can get some pointers I should be able to work with it.

Any help truly appreciated.

+1  A: 

This will find all the divs on the page and set their widths equal to their img child element's width.

 $('.divselector').attr('width', $(this).find('img').attr('width'))
Joey C.
Just make sure you add a class to the divs and use that to select the divs. Otherwise, this will apply to ALL divs in the DOM.
John P Bloch
+1  A: 

This works perfectly. Note that you have to use $(window).load() instead of $(document).ready(), because $(document).ready() fires before images are actually loaded, and thus the images will have no width.

$(window).load(function() {
    $('div').each(function() {
        $(this).width($(this).find('img').width());
    });
});

Edit: Note that this will base the width off of the first image in the div. Simply change the index ([0]) to base it off another image in the div.

Edit 2: Applied John's correction on the .width() function.

Ryan Kinal
This is a little bit klunky. For example, width() returns only the width of the first selected element anyway, so the whole declaration of `img` is redundant.Also, the on window load isn't good because it will wait for the whole page to finish loading. Putting the script in the footer will work just fine.
John P Bloch
@John You're right about width(). However, the window load is necessary. We *want* to wait until all the content has loaded, because unless the width of the images is specifically declared, the browser will not know how wide the image is, even once the element has been parsed.
Ryan Kinal
Hi guys, thanks for the pointers. I have uploaded the example 'proof of concept' I am working with to get this working here if you are interested:www.simonlast.co.uk/example/04.html Seems to be working, though it appears there may be some unexpected interaction with masonry but I think that is something I can tweak.Thanks for the help, much appreciated.
theothersimon
Hi All,If you check this example:www.simonlast.co.uk/example/04.htmlyou can its its all running well in ff, chrome and safari, but I am getting an 'invalid argument' error in IE8. It appears to be something to do with the parent resizing script, any clues as to why? And how to fix it?
theothersimon