6

A bit of (JS-modified) HTML might look like this:

<div style="width: 50px;">1,234,567</div>

How do I detect if the text node is wider than the container?

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
  • I'd guess it'll involve cloning the text node, and dropping it into a container that doesn't have a fixed width, or if you can change the markup, wrap the text content in a ``, and use the width of that instead. –  Aug 14 '12 at 19:39
  • possible duplicate of [How to detect overflow in div element?](http://stackoverflow.com/questions/7138772/how-to-detect-overflow-in-div-element). Just use `scrollWidth` instead of `scrollHeight` – Matt Ball Aug 14 '12 at 19:39
  • @MattBall That seems useful, but I don't have hidden overflow on the element. Will I have to add that, or will it work without an overflow setting? – Niet the Dark Absol Aug 14 '12 at 19:52
  • It works without `overflow: hidden`. http://jsfiddle.net/mattball/pYj5P/ – Matt Ball Aug 14 '12 at 20:08
  • Oh, well that's excellent. If you could make that an answer I'll gladly Accept it. – Niet the Dark Absol Aug 14 '12 at 20:17
  • Only if you vote to close as a dup as well `:)` – Matt Ball Aug 14 '12 at 20:20

1 Answers1

7

As inspired by How to detect overflow in div element?:

<!-- Overflowing -->
<div style="width: 50px;">1,234,567</div>

<!-- Not overflowing -->
<div>1,234,567</div>

JavaScript (no jQuery) to detect:

var divs = document.getElementsByTagName('div');
var i, div, overflowing;

for (i=0; i<divs.length; i++) {
    div = divs[i];
    overflowing = div.offsetWidth < div.scrollWidth;
    console.log(overflowing);
}​

http://jsfiddle.net/mattball/pYj5P/

Community
  • 1
  • 1
Matt Ball
  • 354,903
  • 100
  • 647
  • 710
  • Result is `false` in both cases in Firefox, as I would imagine it should be. Since it's allowed to visibly overflow, there wouldn't be anything to scroll. –  Aug 14 '12 at 20:45
  • @amnotiam that's part of why I put the border in. With Chrome, the right border on the first div crosses the `6`: http://i.stack.imgur.com/N3MrS.png and correspondingly, the code prints `true` for the first div only. – Matt Ball Aug 14 '12 at 20:52
  • 1
    Yes, I understand why the border was there. I used [background instead](http://jsfiddle.net/7b3nk/) to make it a little easier to see. My point is that Firefox gives a different result. The code prints `false` for both divs because the `scrollWidth` is equal to the `offsetWidth` when the overflow is visible. I'm assuming the Firefox result is the correct one, since the content can't be scrolled when its overflow is visible. –  Aug 14 '12 at 20:56