Detecting Content Overflow in HTML Elements Without Scrollbars
Many developers face the challenge of determining when an HTML element's content extends beyond its visible boundaries, especially if scrollbars are not present. This task becomes more complex when the element's overflow property is set to "visible."
Solution
The solution lies in comparing the element's client dimensions ([Height|Width]) with its scroll dimensions ([Height|Width]). However, when overflow is visible, these values will be equal. To account for this, we can temporarily modify the overflow style to "hidden," check for overflow conditions, and then restore the original overflow value.
Implementation
The code snippet below provides a JavaScript function, checkOverflow(), that performs this detection:
// Determine if the passed element is overflowing its bounds, // either vertically or horizontally. // Will temporarily modify the "overflow" style to detect this // if necessary. function checkOverflow(el) { var curOverflow = el.style.overflow; if ( !curOverflow || curOverflow === "visible" ) el.style.overflow = "hidden"; var isOverflowing = el.clientWidth < el.scrollWidth || el.clientHeight < el.scrollHeight; el.style.overflow = curOverflow; return isOverflowing; }
Usage
Call the checkOverflow() function on the target element to determine if it has any overflowed content. The function returns a Boolean value indicating whether or not overflow is present.
Testing
This routine has been tested successfully in Firefox 3, Firefox 40.0.2, Internet Explorer 6, and Chrome 0.2.149.30.
The above is the detailed content of How Can I Detect HTML Content Overflow Without Scrollbars?. For more information, please follow other related articles on the PHP Chinese website!