I need to adjust the width of an element based on parent’s width and add an ellipsis at the end. Here’s what I’ve got. Looks straight forward but I can’t seem to be able to add ellipsis. What did I miss?
<style>
.myClass{
white-space: nowrap;
overflow: hidden;
}
</style>
$(".myClass").each(function() {
var str = $(this);
var par = str.parent().width();
var newWidth = par - 20; // to allow room for ellipsis
str.width(newWidth);
str.append("...");
});
<div style="width: 100px">
<span class="myClass">My long text string here. Even longer goes on and on.</span>
</div>
Had to make a few changes. The biggest is that
display:hiddenmeans that the...you add will be clipped off. You need to append that...to the parent element. Also, I changed thespantodisplay:inline-block;so thatdisplay:hiddenwould work properly.http://jsfiddle.net/u6XfD/
Note: This is not a great idea since as you can see in that fiddle, it may cut characters off in the middle.