Show ellipsis by jQuery
by ginpei
HTML
<div class="text-overflow with-height-limit">
<p>This is a long long long long long long long long long long text</p>
</div>
<div class="text-overflow with-height-limit">
<p>This is a short text.</p>
</div>
<div class="text-overflow with-height-limit">
<p>This is an another long long long long long long long long long long text</p>
</div>
CSS
.text-overflow {
border: solid 1px #ccc;
box-shadow: 1px 1px 4px rgba(0,0,0,.1) inset;
line-height: 1.5em;
margin: 1em;
overflow: hidden;
padding: 4px;
position: relative;
width: 200px;
}
.text-overflow .ellipsis {
background-color: #fff;
bottom: 0;
position: absolute;
right: 4px;
}
.with-height-limit {
height: 3em;
}
h1 {
font-weight: bold;
}
h1::after {
content: ":"
}
JavaScript
jQuery(function($) {
$('.with-height-limit').each(function(index, node) {
var $outer = $(this);
// wrap all children
$outer.wrapInner('<div />');
var $inner = $outer.children();
// get heights of them
var outerHeight = $outer.height();
var innerHeight = $inner.height();
// show ellipsis if inner block is higher than outer
if (innerHeight > outerHeight) {
$('<span />', {
"class": 'ellipsis',
text: '…'
})
.appendTo($outer);
}
});
});