EN
JavaScript - detect if text overflows element vertically
3
points
In this article, we would like to show you how to detect if text overflows element vertically in JavaScript.
Quick solution:
function isTextOverflowing(element) {
return (element.clientHeight < element.scrollHeight);
}
// Usage example:
const element = document.querySelector('#element');
if (isTextOverflowing(element)) {
// ...
}
Practical example
In this example, we check if the element's clientHeight
value is less than its scrollHeight
to determine if the text is overflowing the element vertically.
// ONLINE-RUNNER:browser;
<!doctype html>
<html>
<head>
<style>
div.text {
padding: 5px;
border: 1px solid red;
width: 200px; /* <------ limits element width */
height: 23px; /* <------ limits element height */
white-space: nowrap; /* <------ prevents text from wrapping */
overflow: hidden; /* <------ hides content overflowing */
}
</style>
</head>
<body>
<div id="text-1" class="text">
Short text
</div>
<div id="text-2" class="text">
1<br />
2<br />
3<br />
</div>
<script>
function isTextOverflowing(element) {
return (element.clientWidth < element.scrollWidth || element.clientHeight < element.scrollHeight);
}
// Usage example:
const text1 = document.querySelector('#text-1');
const text2 = document.querySelector('#text-2');
console.log(isTextOverflowing(text1)); // false
console.log(isTextOverflowing(text2)); // true
</script>
</body>
</html>