JSFiddle - React, Tailwind, and code Playground

by Kearnan Kelly

JavaScript

// custom method to fit text into its container
BISN.truncateTextToFit = function(container) {
    // 18 & 24 cludge to allow for line-height could be cleaner
    var x = $(container).width() - 18;
    var y = $(container).height() - 24;

    var p = '';
    var c = 0;
    var currentX1;
    var currentX2;
    var currentY1;
    var currentY2;
    
    // get the original text we got from the server
    // the page may have just changed size
    var parag = $.trim($(container).attr('data'));
    var words = parag.split(' ');
    c = words.length;
    var saver = '';
    // iterate through the text and test
    // each word to see if it lay beyond
    // the bounds of enclosing rectangle
    for (var i = 0; i < c; i++)
    {
        p = '';
        // load the text as it is now
        $(container).html(parag);
        // incrementally wrap each word with a span
        for (var w = 0; w < c; w++)
        {
            if (w === i)
            {
                // save the text as it is right now
                saver = p + "...";
                p += '<span class="wPos">' + words[w] + '</span> ';
            }
            else
            {
                p += words[w] + ' ';
            }
        }
        // put the text back with one word wrapped
        $(container).html(p);

        // see if the position of that word is passed our boundary
        if ($('.wPos').size() > 0) {
            currentX1 = $('.wPos').position().left;
            currentX2 = currentX1 + $('.wPos').width();
            currentY1 = $('.wPos').position().top;
            currentY2 = currentY1 + $('.wPos').height();
            // if this is the end, set the text, stop looking and leave
            if ((currentX2 > x) && (currentY2 > y))
            {
                $(container).html(saver);
                return;
            }
        }
    }
};