javascript - .offsetWidth, .width, .width() etc. not always returning properly on auto-sized element -


i'm trying resize div based on width of image contained within it, no js method grabbing image's width seems 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 .style.width, .width, .offsetwidth, .width(), .outerwidth(), .getboundingclientrect.width() each of these, correctly grabs image width of time, other times has image's width 0. (or 2 because has 1px border , that's part getting picked up, same deal.) issue grabbing of width, not setting, tested alerts.

the reason need resize div image caption wrap if it's wider image itself.

is there obvious i'm missing, either reason happening or better way solve problem?

thanks!

i believe issue image has load before size set. js executing before happens, not reliably. try waiting image finish loading before attempt set size:

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

Comments

Popular posts from this blog

angular - Ionic slides - dynamically add slides before and after -

minify - Minimizing css files -

Add a dynamic header in angular 2 http provider -