JSFiddle - React, Tailwind, and code Playground

by Jason Crowther

HTML

<div id="target" class="truncateMiddle" title="ok, lets put some really long text in here and see if it works."></div>

CSS

#target { background-color: yellow; width: 10em; }
.truncateMiddle { font-size: 90% }

JavaScript

console.log( $('#target').attr('title'));

var text = $('#target').attr('title');

var $sizer = $('<span class="truncateMiddle" style="display:inline; visibility:hidden;padding:0"></span>');

$('body').append($sizer);

var width=$('#target').width();
console.log('width',width);

$sizer.text( $('#target').attr('title') );

var checkWidth = $sizer.width();
console.log('checkWidth',checkWidth);

var ret = text;

if( checkWidth > width ) {
     console.log('too wide');
    
    
    while( checkWidth > width ) {
           text = text.replace(/.$/,'');
           text = text.replace(/\s+$/,'');
            ret = text + '...';
            //console.log('ret',ret);
            $sizer.text(ret);
            checkWidth = $sizer.width();
    }
}

console.log('final',ret)

$('#target').text( ret);

$sizer.remove();