Shivagoy
Shivagoy

Reputation: 383

How to get Current HTML element height and width property in javascript function

I want to access height and width property of current html img element to apply ngClass dynamically based on property.

I have this code for html

<div class="cfg-pg-outer-box" ng-repeat="album in album_list">
    <div class="cfg-pg-photo-box">
        <img ng-src="{{album.thumbnail.image_path}}" ng-class="myclass(this)">
    </div>
</div>

I am using AngularJS to apply ngClass dynamically

$scope.myclass = function(element) {    
    return (element.width > element.height ? 'landscape' : 'portrait');
}

I am not able to read width and height properties. Do you have any suggestion?

Upvotes: 2

Views: 1753

Answers (5)

Chaitanya
Chaitanya

Reputation: 77

var width = document.getElementById('<Element's ID>').offsetWidth;
var height= document.getElementById('<Element's ID>').offseHeight;

Upvotes: 1

Rahul Desai
Rahul Desai

Reputation: 15501

var height = document.body.clientHeight;
var width = document.body.clientWidth;

Explanation

EDIT:

In response to your comment, try using:

var element = document.getElementById("elementId");

var height = element.style.height;
var width =  element.style.width;

EDIT2:

You might also wanna try:

document.getElementById(id_attribute_value).offsetHeight;

and/or

document.getElementById(id_attribute_value).clientHeight;

Upvotes: 0

Dev Logicbox
Dev Logicbox

Reputation: 51

You need to use $scope.$apply, otherwise any changes to $scope made in non-Angular event handlers won't be processed properly:

$scope.myclass = function(element) {

$scope.image.width = img.width;
$scope.image.height = img.height;
$scope.image.path = $scope.imageurl;
$scope.$apply();

   return (this.width > this.height ? 'landscape' : 'portrait');

}

Upvotes: 1

dfsq
dfsq

Reputation: 193271

The problem with your attempt is that unlike regular HTML event attributes like onclick, ngClass and similar have different context of invocation. To be exact this points to current scope object.

In your case you should write a custom directive to read/operate with DOM element. For example simple directive can look like:

app.directive('dimentionClass', function() {
    return {
        link: function(scope, element) {
            var img = element[0];
            img.onload = function() {
                img.className = img.width > img.height ? 'landscape' : 'portrait';
            }
        }
    };
});

and you will use it like this:

<img ng-src="{{album.thumbnail.image_path}}" dimention-class />

Demo: http://plnkr.co/edit/GtklqTUvtbFxb6AFuz4S?p=preview

Upvotes: 2

Ivan Tilikin
Ivan Tilikin

Reputation: 103

use element.offsetWidth and element.offsetHeight

Upvotes: 1

Related Questions