Reputation: 282895
I want to determine if a block of text is cut-off/showing an ellipsis so that I can conditionally add a [more]
link after it.
Here's the CSS I'm using:
.more-text-collapse {
display:inline-block;
max-width:400px;
height:1.2em;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
Which I apply to a <div>
. When the text inside exceeds 400px it displays an ellipsis at the end. In that scenario I want to add a [more]
link to expand the text.
How can I determine if I need to display the link?
Upvotes: 3
Views: 1208
Reputation: 311
according to this answer, here you go with the code:
$.fn.textWidth = function(){
var html_org = $(this).html();
var html_calc = '<span>' + html_org + '</span>';
$(this).html(html_calc);
var width = $(this).find('span:first').width();
$(this).html(html_org);
return width;
};
var elmW = $('.more-text').width(),
txtW = $('.more-text').textWidth();
if(elmW < txtW) $('.more-text').after('[more]');
http://jsfiddle.net/Sergiu/EvD3J/1/
Upvotes: 2
Reputation: 282895
Looks like I can do what I want using these styles:
.more-text {
line-height: 1.2em;
display:none;
white-space: nowrap;
}
.more-text-collapse {
display:inline-block;
max-width:400px;
height:1.2em;
overflow:hidden;
text-overflow:ellipsis;
white-space:nowrap;
}
.more-text-expand {
display:inline;
white-space: pre-wrap;
}
I give each of <divs>
just the more-text
class which lets them spread to their full width but hides them so they don't muck up the interface, then I compute their width and override class:
$('.more-text').each(function(i,el) {
var width = $(this).width();
$(this).addClass('more-text-collapse');
if(width > 400) {
$('<a>', {href:'#',class:'more-link'}).text('[more]').insertAfter(this);
}
});
Actually, we can take the width out of the CSS entirely so that we only have to define it in one place:
var maxWidth = 400;
$('.more-text').each(function(i,el) {
var width = $(this).width();
if(width > maxWidth) {
$(this).addClass('more-text-collapse').css('max-width',maxWidth);
$('<a>', {href:'#',class:'more-link'}).text('[more]').insertAfter(this);
} else {
$(this).addClass('more-text-expand');
}
});
Would be nice if I could animate the text expanding...
Upvotes: 0