The problem is that #txt
is floated to the right, so it overflows towards the left.
But with the default left-to-right direction it's not possible to scroll towards the left.
However, you can if you use a right-to-left direction
#z { direction: rtl; }
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;
}
console.log(checkOverflow(document.getElementById('z')));
div#z {
position: relative;
background: red;
width: 50px;
height: 50px;
overflow: auto;
direction: rtl;
}
div#txt {
background: lightblue;
float: right;
}
<div style="float:right;">
<div id="z">
<div id="txt">
345345345345345345345345345345345
</div>
</div>
</div>
Of course, if then content overflows towards the right (e.g. you change to float: left
), you will have the same problem.
If you want a more general approach, you can use getBoundingClientRect
:
var rect = el.getBoundingClientRect();
var isOverflowing = [].every.call(el.children, function(child) {
var childRect = child.getBoundingClientRect();
return childRect.left < rect.left
|| childRect.right > rect.right
|| childRect.top < rect.top
|| childRect.bottom > rect.bottom;
});
function checkOverflow(el) {
var curOverflow = getComputedStyle(el).overflow;
if (!curOverflow || curOverflow === 'visible')
el.style.overflow = 'hidden';
var rect = el.getBoundingClientRect();
var isOverflowing = [].every.call(el.children, function(child) {
var childRect = child.getBoundingClientRect();
return childRect.left < rect.left
|| childRect.right > rect.right
|| childRect.top < rect.top
|| childRect.bottom > rect.bottom;
});
el.style.overflow = curOverflow;
return isOverflowing;
}
console.log(checkOverflow(document.getElementById('z')));
div#z {
position: relative;
background: red;
width: 50px;
height: 50px;
overflow: auto;
}
div#txt {
background: lightblue;
float: right;
}
<div style="float:right;">
<div id="z">
<div id="txt">
345345345345345345345345345345345
</div>
</div>
</div>