Search code examples
javascriptjqueryellipsis

Get only the ellipsis text using jquery


Nice code, just wondered if it is possible to query and get the ellipsis text (i.e. with the dots in and not the original text)?

If I add the text

This is a long sentence

and (using the relevant css for ellipsis) it gets shortened to

This is a long sen ...

Is there a way to get the text

"This is a long sen ..." 

from the $("p") DOM object rather than the original text?


Solution

  • I have a rough draft that needs some browser-specific tweaking.

    JavaScript:

    jQuery.fn.getShowingText = function () {
        // Add temporary element for measuring character widths
        $('body').append('<div id="Test" style="padding:0;border:0;height:auto;width:auto;position:absolute;display:none;"></div>');
        var longString = $(this).text();
        var eleWidth = $(this).innerWidth();
        var totalWidth = 0;
        var totalString = '';
        var finished = false;
        var ellipWidth = $('#Test').html('&hellip;').innerWidth();
        var offset = 7; // seems to differ based on browser (6 for Chrome and 7 for Firefox?)
        for (var i = 0;
        (i < longString.length) && ((totalWidth) < (eleWidth-offset)); i++) {
            $('#Test').text(longString.charAt(i));
            totalWidth += $('#Test').innerWidth();
            totalString += longString.charAt(i);
            if(i+1 === longString.length)
            {
                finished = true;
            }
        }
        $('body').remove('#Test'); // Clean up temporary element
        if(finished === false)
        {
            return totalString.substring(0,totalString.length-3)+"…";
        }
        else
        {
            return longString;
        }
    }
    console.log($('#ellDiv').getShowingText());
    

    CSS:

    #Test {
        padding:0;
        border:0;
        height: auto;
        width: auto;
        position:absolute;
        white-space: pre;
    }
    div {
        width: 100px;
        white-space: nowrap;
        border: 1px solid #000;
        overflow:hidden;
        text-overflow:ellipsis;
        padding:0;
    }
    

    With the caveat that the offset needs to change depending on the browser, unless someone can figure out what is causing it.

    I suspect letter-spacing or similar?