Search code examples
javascripthtmlcssarraysellipsis

How can show number + more of remain text from string array fixed to div width by using javascript and css?


enter image description here

I want to show string array separated by commas in div has width(ex: 300px). When text's longer than div width, it will show text has three dots and + (number of remain texts in array) like the picture above.

Thanks.


Solution

  • How about this?

    var main = document.querySelector('main');
    var p = document.querySelector('p');
    var stringArr = ['Apple', 'Grape fruit', 'Orange', 'Banana', 'KiwiJuice', 'Tangerine'];
    
    function dotdotdot(list){
      var ix, ixLen, listLen;
      var span = document.createElement('span');
      span.textContent = ' + ';
      
      // 1. insert a text into an element
      // 2. compare the scrollWidth and the clientWidth
      //    if scrollWidth is bigger than the other, it means the text has been overflowed
      // 3. find the index of the text which has been overflowed
      // 4. insert <span>+ ?more</span>
      // * when compare two scrollWidths, consider the width of <span> because of the max-width of <main> tag. 
      // * the width of <span> is set by 150 px as an example.
      for(ix = 0, ixLen = list.length; ix < ixLen; ix++){
         if(ix !== ixLen - 1){
           //main.textContent += list[ix] + ', ';
           p.textContent += list[ix] + ', ';
         }else{
           //main.textContent += list[ix];
           p.textContent += list[ix];
         }
         
         if(p.scrollWidth > main.scrollWidth - 150){
           //p.style.overflow = 'hidden';
           //p.style.textOverflow = 'ellipsis';
           p.style.width = p.clientWidth + 'px';
           
           span.textContent += list.length - (ix + 1);
           span.textContent += 'more';
           main.append(span);
           return;
         }
      }
    }
    
    dotdotdot(stringArr);
    main {
      max-width: 300px;
      height: 30px;
      border: 1px solid #000000;
    }
    
    p {
      display: inline-block;
      width: fit-content;
      margin: 0;
      white-space: nowrap;
      text-overflow: ellipsis;
      overflow: hidden;
    }
    <main>
      <p></p>
    </main>