-
Notifications
You must be signed in to change notification settings - Fork 894
/
measureTextWidth.js
40 lines (35 loc) · 1.17 KB
/
measureTextWidth.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
const elementId = "yoast-measurement-element";
/**
* Creates an hidden element with the purpose to calculate the sizes of elements and adds these elements to the body.
*
* @returns {HTMLElement} The created hidden element.
*/
function createMeasurementElement() {
const hiddenElement = document.createElement( "div" );
hiddenElement.id = elementId;
// Styles to prevent unintended scrolling in Gutenberg.
hiddenElement.style.position = "absolute";
hiddenElement.style.left = "-9999em";
hiddenElement.style.top = 0;
hiddenElement.style.height = 0;
hiddenElement.style.overflow = "hidden";
hiddenElement.style.fontFamily = "Arial";
hiddenElement.style.fontSize = "16px";
hiddenElement.style.fontWeight = "400";
document.body.appendChild( hiddenElement );
return hiddenElement;
}
/**
* Measures the width of the text using a hidden element.
*
* @param {string} text The text to measure the width for.
* @returns {number} The width in pixels.
*/
export default function measureTextWidth( text ) {
let element = document.getElementById( elementId );
if ( ! element ) {
element = createMeasurementElement();
}
element.innerHTML = text;
return element.offsetWidth;
}