Anon
Anon

Reputation: 1221

Truncate a string with the remaining space

I have a list where each li element contains two div inside one div "main" :

=> I wish text inside div "part2" had as width that of div "main" less div "part1" (the remaining space)

EX:

...
<li>
   <div class="main">   
          <div class="part1">A</div>
          <div class="part2">BlaBlaBla</div>
   </div>   
</li>
<li>
   <div class="main">   
          <div class="part1">ABC</div>
          <div class="part2">BlaBlaBla</div>
   </div>   
</li>
<li>
   <div class="main">   
          <div class="part1">ABCDE</div>
          <div class="part2">BlaBlaBla</div>
   </div>   
</li>
...

It should display:

A BlaBla...
ABC BlaB...
ABCDE Bl...

I tried but it doesn't work :

$(function(){
  $(".part1").each(function(){
    var $this = $(this);
    var $len = 0;
    var $len = $this.outerWidth();
    var $lenParent =$this.parent().outerWidth();        
    var newText2 = $this.next('.part2').text().substring(0,$lenParent-$len); 
    $this.next('.part2').innerHtml(newText2+"...");
  });
});

Upvotes: 0

Views: 168

Answers (2)

Nope
Nope

Reputation: 22339

Using the display: inline of Thinking Sites's answer and the ellipse styles as suggested by epascarello this complete solution will now work:

.main{
    width: 100px;
    border: 1px solid red;
    text-overflow: ellipsis;
    overflow: hidden;
    white-space: nowrap;
}

.part1, .part2{
    display: inline;
}

See DEMO

Upvotes: 1

Thinking Sites
Thinking Sites

Reputation: 3542

You don't need JavaScript for this, it can be done with styles. Change the css for part1 and part2 to display:inline

.part1,.part2
{
    display:inline;
}

Upvotes: 1

Related Questions