I\'ve seen this question but feel like there has to be a \"cleaner\" jQuery method of doing this. I\'m not even sure if this really works in all scenarios. Is there a way fo
$.fn.hasOverflow = function() {
var $this = $(this);
var $children = $this.find('*');
var len = $children.length;
if (len) {
var maxWidth = 0;
var maxHeight = 0
$children.map(function(){
maxWidth = Math.max(maxWidth, $(this).outerWidth(true));
maxHeight = Math.max(maxHeight, $(this).outerHeight(true));
});
return maxWidth > $this.width() || maxHeight > $this.height();
}
return false;
};
Example:
var $content = $('#content').children().wrapAll('<div>');
while($content.hasOverflow()){
var size = parseFloat($content.css('font-size'), 10);
size -= 1;
$content.css('font-size', size + 'px');
}
A simple solution I have found is to detect the scrollWidth
of the parent()
:
var totalWidth = $(this).parent()[0].scrollWidth;
0
index is referring to the "root node" of the parent, obtaining the property from there.
You may change the css attributes to fit your needs.
$.fn.hasOverflow = function() {
$(this).css({ overflow: "auto", display: "table" });
var h1 = $(this).outerHeight();
$(this).css({ overflow: "hidden", display: "block" });
var h2 = $(this).outerHeight();
return (h1 > h2) ? true : false;
};
There is no clean method. You could make it two wrappers, the outer wrapper having overflow: hidden
, and comparing the two wrappers' dimensions, but anything you could possibly do would end up being hacky. If the functionality really is necessary, then you'll have to live with the hacks.
There exists another solution, (this example tests if the height overflows) it requires the overflowing container to be position:relative
:
<div id="overflowing-container" style="position:relative">
<div class="children"></div>
<div class="children"></div>
<div class="children"></div>
</div>
var last = $('.children:last'), container=$('#overflowing-container')
lastOffsetHeight = container.scrollTop() + last.outerHeight(true) + last.position().top;
if (last[0] && lastOffsetHeight > container[0].getBoundingClientRect().height) {
console.log("thisContainerOverflows")
}