Calculate the width of a text, and shorten it to a number of pixels given in JavaScript

In some cases we may need to calculate from JavaScript the width of a text on the screen.
To do this we will use a layer that will make us as a rule. This layer must have the same styles that the fate of the text that we want to measure, or assigning these styles whenever we are going to measure.

This is the HTML for the layer:

<span id="ruler"></span>

The layer has to be hidden with the following CSS:

#ruler {
	visibility: hidden;
	white-space: nowrap;
	position: absolute;
	top: -100;
	left: 0px;
}

And finally we will extend the string class in JavaScript with two methods that will allow us to calculate the width of a text in pixels and trim a text to a specified width.

// Calcula los pixeles de ancho que ocupa un texto
String.prototype.visualLength = function() {
    var ruler = document.getElementById("ruler");
    ruler.innerHTML = this;
    return ruler.offsetWidth;
}

// Recorta un texto al número de pixeles indicados, añadiendo un "..." en el caso de haber sido recortado
String.prototype.trimToPx = function(length)
{
    var tmp = this;
    var trimmed = this;
    if (tmp.visualLength() > length)
    {
        trimmed += "...";
        while (trimmed.visualLength() > length)
        {
            tmp = tmp.substring(0, tmp.length-1);
            trimmed = tmp + "...";
        }
    }

    return trimmed;
}

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *

Este sitio usa Akismet para reducir el spam. Aprende cómo se procesan los datos de tus comentarios.

Loading Facebook Comments ...