0
votes

I'm trying to resize a div based on the width of an image contained within it, but no JS method for grabbing the image's width seems to be working consistently.

<div class="main_image">
     <img class="wp-post-image" src="">
     <label>label here</label>
</div>

img {
    width: auto;
    height: auto;
    max-width: 500px;
    max-height: 450px;
}

var newWidth = document.getElementsByClassName("wp-post-image"[0].offsetWidth;
$(".wp-post-image").parent(".main_image").css({"width": newWidth});

I've tried with .style.width, .width, .offsetWidth, .width(), .outerWidth(), .getBoundingClientRect.width() For each of these, it correctly grabs the image width some of the time, but other times it has the image's width as 0. (Or 2 because it has a 1px border and that's the only part getting picked up, same deal.) The issue is definitely the grabbing of the width, not the setting, as tested with alerts.

The reason I need to resize this div is so that the image caption will wrap if it's wider than the image itself.

Is there something obvious I'm missing, either a reason this is happening or a better way to solve my problem?

Thanks!

1
are you getting console errors in you jQuery or javascript?DraganAscii

1 Answers

1
votes

I believe the issue is that your image has to load before the size is set. Your JS is executing before this happens, but not reliably. Try waiting for the image to finish loading before you attempt to set the size:

$('img').on('load', function() {
    var newWidth = $(".wp-post-image").first().width();
    $(".wp-post-image").parent(".main_image").css("width", newWidth);
});