Reputation: 12034
Let’s say I have a title in h1 element (any element would do). Its content is dynamic (do not know length of the title). It is supposed to be displayed in one line. h1 is in a DIV (let’s call it a container) of limited size.
How do I know if element (h1) overflows its container (DIV)?
So that if it overflows I would apply a CSS class to deal with the situation. For example I would scroll hidden content of h1 into view.
Example:
#container {
width: 60%;
background-color: gray;
height: 50px;
// overflow: hidden;
position: relative;
}
h1 {
overflow: hidden;
height: 100%;
margin: 0;
line-height: 50px;
}
<div id="container">
<h1>a soft white or grey mineral consisting of hydrated calcium sulphate. It occurs chiefly in sedimentary deposits and is used to make plaster of Paris and fertilizers, and in the building industry.</h1>
</div>
Best solution would be if it could be used in: primary in ngIf
, secondary in ngClass
directives, but any of following technologies are also good: Javascript
, AngularJS
, CSS
, AngularJS directive
.
Upvotes: 1
Views: 1728
Reputation: 12034
Here is my solution in AngularJS directive
. It does not rely on parent element:
var myDirective = angular.module('myDirective', []);
myDirective.directive( 'myDirective' , ['$timeout' , function($timeout) {
return {
link: function (scope , element , attrs) {
// Wait few milliseconds until element is re-rendered
// so that element properties reflect content size.
$timeout( function(){
if (element[0].scrollWidth > element[0].offsetWidth){
// overflow
}
}, 200); // $timeout
} // link
}; // return
}]); // myDirective
Usage example:
<h3 my-directive>Hello World!</h3>
Note: Parent element must have restricted size otherwise it will adjust to the content and element will never overflow.
Upvotes: 1
Reputation: 566
Assuming jquery you could check widths of the elements.
if ($('h1').scrollWidth > $('#container').innerWidth()) {
//overflown
}
Upvotes: 1