Abhishek Pandey Abhishek Pandey - 3 months ago 10
HTML Question

Add class when div tag is getting overflowed

I have a

div
with fixed height and width, I'm adding some content in it using
ng-repeat
, I want to add a class on this div when this is getting overflowed. I tried to add class with
length
but didn't work.



var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {
$scope.placeholder = ['Koenigsegg CCXR Trevita',
'Lamborghini Veneno',
'W Motors Lykan Hypersport',
'Bugatti Veyron',
'Ferrari Pininfarina Sergio',
'Pagani Huayra BC',
'Ferrari F60 America',
'Bugatti Chiron',
'Koenigsegg One',
'Koenigsegg Regera'
];
});

div {
height: 40px;
width: 400px;
background: #f2f2f2;
padding: 5px;
}
span {
border: 1px solid #999;
padding: 3px;
display: inline-block;
margin: 2px;
border-radius: 3px;
}

<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="personCtrl">
<span ng-repeat="j in placeholder;">
{{j}} &times;
</span>

</div>





Note: I can only use
javascript
or
angularjs

Answer

If you need only to add some class when there is too much items in array, you can use ng-class attribute.

var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope) {

});
div{height:100px;width:100px;background:#f2f2f2;border:1px solid #000}
div.too-long {background-color: #FF6666}
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="personCtrl" ng-class="{'too-long': placeholder.length > 6}" ng-init="placeholder=[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]">
  <span ng-repeat="j in placeholder;">
    {{j}} Content
  </span>

</div>

But if you need to compare content size and div size, you can use offsetHeight and scrollHeight properties of your div

var app = angular.module('myApp', []);
app.controller('personCtrl', function($scope, $element) {
    $scope.placeholder = [1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18]
    $scope.overflow = function() {
        return $element[0].scrollHeight > $element[0].offsetHeight;
    }
});
div{height:100px;width:100px;background:#f2f2f2;border:1px solid #000}
div.too-long {background-color: #FF6666}
<script src="http://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

<div ng-app="myApp" ng-controller="personCtrl" ng-class="{'too-long': overflow()}">
  <span ng-repeat="j in placeholder;">
    {{j}} Content
  </span>

</div>