Check with jquery if div has overflowing elements
You actually don't need any jQuery to check if there is an overflow happening or not. Using element.offsetHeight
, element.offsetWidth
, element.scrollHeight
and element.scrollWidth
you can determine if your element have content bigger than it's size:
if (element.offsetHeight < element.scrollHeight ||
element.offsetWidth < element.scrollWidth) {
// your element have overflow
} else {
// your element doesn't have overflow
}
See example in action: Fiddle
But if you want to know what element inside your element is visible or not then you need to do more calculation. There is three states for a child element in terms of visibility:
If you want to count semi-visible items it would be the script you need:
var invisibleItems = [];
for(var i=0; i<element.childElementCount; i++){
if (element.children[i].offsetTop + element.children[i].offsetHeight >
element.offsetTop + element.offsetHeight ||
element.children[i].offsetLeft + element.children[i].offsetWidth >
element.offsetLeft + element.offsetWidth ){
invisibleItems.push(element.children[i]);
}
}
And if you don't want to count semi-visible you can calculate with a little difference.
Partially based on Mohsen's answer (the added first condition covers the case where the child is hidden before the parent):
jQuery.fn.isChildOverflowing = function (child) {
var p = jQuery(this).get(0);
var el = jQuery(child).get(0);
return (el.offsetTop < p.offsetTop || el.offsetLeft < p.offsetLeft) ||
(el.offsetTop + el.offsetHeight > p.offsetTop + p.offsetHeight || el.offsetLeft + el.offsetWidth > p.offsetLeft + p.offsetWidth);
};
Then just do:
jQuery('#parent').isChildOverflowing('#child');
I had the same question as the OP, and none of those answers fitted my needs. I needed a simple condition, for a simple need.
Here's my answer:
if ($("#myoverflowingelement").prop('scrollWidth') > $("#myoverflowingelement").width() ) {
alert("this element is overflowing !!");
}
else {
alert("this element is not overflowing!!");
}
Also, you can change scrollWidth
by scrollHeight
if you need to test the either case.