angularjs how to find img element height and width

10,313

See code below:

.directive('lightboxResizeImage', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
             console.log(elem.parent().width()); // =575
             console.log(elem[0].offsetHeight);
        }
    }
});
Share:
10,313

Related videos on Youtube

user1424508
Author by

user1424508

Updated on June 25, 2022

Comments

  • user1424508
    user1424508 almost 2 years

    Hi I'm trying to find an image element's height and width in order to resize it. However everytime I use elem.height() or elem.width() I get 0?

    html

    <div>
        <img data-ng-src="{{photosrc}}" lightbox-resize-image>
    </div>
    

    directive.js

    .directive('lightboxResizeImage', function() {
    return {
        restrict: 'A',
        link: function(scope, elem, attrs) {
    
            console.log(elem.parent().width()); //==equals 575
            console.log(elem.width()); //this always equals 0
    
      }
      });
    
    • Kevin B
      Kevin B over 10 years
      Ensure that the image is loaded first.
    • Arun P Johny
      Arun P Johny over 10 years
      elem.on('load', function(){console.log($(this).width())})
    • Kevin B
      Kevin B over 10 years
      i'd suggest only doing the above after ensuring that it doesn't have a width already. a cached image may have already triggered that event.