Skip to content Skip to sidebar Skip to footer

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 (us

Solution 1:

Try that:

functiongetEllipsis(command, characters) {
	for (var i = command.length; i >= 0; i--) {
		if (command.substring(0, i).length < characters) {
			if (i < command.length) {
				command = command.substring(0, i) + "...";
			}
			return command;
		}
	}
}
console.log(getEllipsis("I am a long sentence",16))
console.log(getEllipsis("But I am even longer",20))

Solution 2:

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 elementif(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?

Post a Comment for "Get Only The Ellipsis Text Using Jquery"