Open In App

Calculate the width of the text in JavaScript

Last Updated : 30 Sep, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

Calculating the width of text in JavaScript refers to determining the pixel width that a specific string of text will occupy when rendered in a browser. This is commonly done using the Canvas API or by creating a hidden element with similar styling to measure the text.

Here we have some common approaches to calculating the width of the text in JavaScript

Method 1: Create a new DOM Element and measure its width

A temporary span element is created using createElement(), styled with the necessary font properties, and added to the document. The clientWidth property measures its width in pixels, after which the element is removed using removeChild(), ensuring accurate measurement.

Example: In this example, we calculate the pixel width of the text “Hello World” with a 16px font size. A temporary span is created, styled, measured using clientWidth, and displayed, before being removed from the document.

html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>Calculate text width
        with JavaScript
    </title>
</head>

<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>

    <b>
        Calculate text width
        with JavaScript
    </b>

    <p>
        Text to calculate width is
        "Hello World"
    </p>
    <p>Font size of the text is 16px</p>

    <p>
        Width of the text is:
        <span class="output"></span>
    </p>

    <button onclick="getTextWidth()">
        Calculate text width
    </button>

    <script type="text/javascript">
        function getTextWidth() {

            text = document.createElement("span");
            document.body.appendChild(text);

            text.style.font = "times new roman";
            text.style.fontSize = 16 + "px";
            text.style.height = 'auto';
            text.style.width = 'auto';
            text.style.position = 'absolute';
            text.style.whiteSpace = 'no-wrap';
            text.innerHTML = 'Hello World';

            width = Math.ceil(text.clientWidth);
            formattedWidth = width + "px";

            document.querySelector('.output').textContent
                = formattedWidth;
            document.body.removeChild(text);
        } 
    </script>
</body>

</html>

Output:

Calculate the width of the text in JavaScript

Calculate the width of the text in JavaScript

Method 2: Using the canvas measureText() Method

A canvas element is created, and its 2D context is accessed using getContext(“2d”). The font is specified, and the measureText() method calculates the text dimensions, returning a TextMetrics object. The width property provides the text width in pixels.

Example: In this example we calculate the width of the text “Geeks For Geeks” with a 16px font size using the Canvas API’s measureText() method and displays the width in pixels on the page.

html
<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" 
          content="width=device-width, 
                   initial-scale=1.0">
    <title>Calculate text width with JavaScript</title>
</head>

<body>
    <h1 style="color: green">
        GeeksforGeeks
    </h1>

    <b>Calculate text width with JavaScript</b>

    <p>
        Text to calculate width is
        "Geeks For Geeks"
    </p>

    <p>Font size of the text is 16px</p>

    <p>
        Width of the text is:
        <span class="output"></span>
    </p>

    <button onclick="getTextWidth()">
        Calculate text width
    </button>

    <script type="text/javascript">
        function getTextWidth() {

            inputText = "Geeks For Geeks";
            font = "16px times new roman";

            canvas = document.createElement("canvas");
            context = canvas.getContext("2d");
            context.font = font;
            width = context.measureText(inputText).width;
            formattedWidth = Math.ceil(width) + "px";

            document.querySelector('.output').textContent
                = formattedWidth;
        } 
    </script>
</body>

</html>

Output:

Calculate the width of the text in JavaScript

Calculate the width of the text in JavaScript



Next Article

Similar Reads