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
}
});
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
}
});
Share
Improve this question
asked Dec 16, 2013 at 2:08
user1424508user1424508
3,30113 gold badges42 silver badges67 bronze badges
3
- 1 Ensure that the image is loaded first. – Kevin B Commented Dec 16, 2013 at 2:09
-
9
elem.on('load', function(){console.log($(this).width())})
– Arun P Johny Commented Dec 16, 2013 at 2:16 - 1 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. – Kevin B Commented Dec 16, 2013 at 2:16
1 Answer
Reset to default 2See code below:
.directive('lightboxResizeImage', function() {
return {
restrict: 'A',
link: function(scope, elem, attrs) {
console.log(elem.parent().width()); // =575
console.log(elem[0].offsetHeight);
}
}
});