0

I have a image element with css set

height: 64px;
width: auto;

When i try to get height and width through jQuery using .outerHeight() & .outerWidth(), i can get height correctly but width returns as 0. I have even tried width(), innerWidth() still same.

I have to set the image dynamically. Maybe that is having some issue. Here is the fiddle http://jsfiddle.net/abdulpathan/0vrbnpe3/3

Could someone help me to tackle this.

Thanks

Abdul Pathan
  • 345
  • 3
  • 12
  • 1
    The properties you've mentioned work absolutely fine: https://jsfiddle.net/qm4xp3rv/. It would help to have a complete example of the problem behaviour showing your HTML, JS and all other relevant CSS – Rory McCrossan Jul 05 '19 at 09:45
  • 1
    ^^ e.g., a [mcve]. Some reasons this happens: The browser hasn't rendered the element yet, the element isn't in the DOM yet, the element is hidden, ... – T.J. Crowder Jul 05 '19 at 09:48
  • I have to set the image dynamically. Maybe that is having some issue. Here is the fiddle https://jsfiddle.net/abdulpathan/0vrbnpe3/3/ – Abdul Pathan Jul 05 '19 at 09:59

1 Answers1

3

The solution is to simply get the width once the image has loaded.

jQuery(document).ready(function() {
  $('#test').on("load", function() {
  
  var height = $('#test').outerHeight();
  var width = $('#test').outerWidth();
  width = width.toFixed(2); // rounds it
  console.log('Width:' + width);
  console.log('Height:' + height);
  })
  $('#test').attr('src', 'https://www.gstatic.com/webp/gallery3/2.png'); 
});
.test-img {
  height: 100px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="banner-message">
  <img id="test" class="test-img">
</div>
  • Thanks, but i dont think that there was need of all such calculations, `$('#test').outerWidth();` work perfectly in `load()`. Because when the image is loaded completely you have all the measurements needed correctly. – Abdul Pathan Jul 09 '19 at 14:47
  • @AbdulPathan You're right! I changed the code accordingly and it's much simpler now :) –  Jul 09 '19 at 18:06