jquerywidthouterwidth

jQuery element outerWidth() returns 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


Solution

  • 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>