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);
}
}
});
Related videos on Youtube
Author by
user1424508
Updated on June 25, 2022Comments
-
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 over 10 yearsEnsure that the image is loaded first.
-
Arun P Johny over 10 years
elem.on('load', function(){console.log($(this).width())})
-
Kevin B over 10 yearsi'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.
-