Element: scrollWidth property - Web APIs | MDN
Value
An integer.
Examples
Detecting overflowing content
In this example, we use the scrollWidth property to check if the content of an element is overflowing its boundaries. We have two div elements, the first with a width of 100px, and the second without a fixed width. Their content is exactly the same, and we display a message about whether each one is overflowing its container.
HTML
html
<div id="div1">FooBar-FooBar-FooBar-FooBar</div>
<button id="button1">Check for overflow</button>
<pre id="log1"></pre>
<div id="div2">FooBar-FooBar-FooBar-FooBar</div>
<button id="button2">Check for overflow</button>
<pre id="log2"></pre>
CSS
css
div {
padding: 0.15em;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
}
button {
margin: 0.15em 0 0.5em 0;
}
pre {
margin: 0.5em 0;
}
#div1 {
width: 100px;
}
#log1 {
margin-bottom: 2em;
}
JavaScript
js
const button1 = document.getElementById("button1");
const button2 = document.getElementById("button2");
const div1 = document.getElementById("div1");
const div2 = document.getElementById("div2");
const log1 = document.getElementById("log1");
const log2 = document.getElementById("log2");
// Check if the scrollWidth is bigger than the clientWidth or not
function isOverflowing(element) {
return element.scrollWidth > element.clientWidth;
}
function checkOverflow(element, log) {
if (isOverflowing(element)) {
log.innerText = `Content is overflowing, scrollWidth is ${element.scrollWidth}px`;
} else {
log.innerText = `No overflows, scrollWidth is ${element.scrollWidth}px`;
}
}
button1.addEventListener("click", () => {
checkOverflow(div1, log1);
});
button2.addEventListener("click", () => {
checkOverflow(div2, log2);
});
Result
Click the buttons to check if the content is overflowing the containers.
Specifications
| Specification |
|---|
| CSSOM View Module # dom-element-scrollwidth |