views:

117

answers:

5

Imagine a website with an element The site wants to run some JS which will fill the div with random text, when the div is full it should clear and start over. Yes I know that sounds weird but the question is, how can the JS know when the div is full, and would start to overflow?

By 'full', I mean no more visible text can be put in the div. I suppose this is the point a scroll bar would become enabled/visible.

+4  A: 

What you could do would be to actually have the text in an inner div, that has the same fixed width as the container, but no fixed height. You'd then let the inner div grow with its content, and check when its height approaches the parent div's fixed height

David Hedlund
A: 

You should be able to get very close by counting the characters in the div. You might need to do this onkeyUp if you're typing, or listen for some other event if it's not being filled by typing.

BrewinBombers
What is the screen resolution at the client? What zoom setting is the browser on? Which font? Character count won't help here, too many variables.
Dave Swersky
specifically, if the div is of a fixed width, i think the biggest deal breaker would be not knowing at what points the text would wrap to a new line
David Hedlund
I guess it depends on the level of accuracy needed, but my solution is clearly not the _best_.
BrewinBombers
+2  A: 

You could compare the actual height of the div against what is defined in the CSS for that div, to see if the actual height is greater - and therefore is 'overflowing'.

if(document.getElementById('div').offsetHeight > 
document.getElementById('div').style.height) {
   //do something
}
James
Would this work, if you force the div to have the desired height? imagine the div is designed to fill a certain part of the page, with border and background color.
John
@John I think this would only work assuming you are not making any modifications to force the height, i.e. you are just using CSS to set the height.
James
A: 

You can't tell if any more text will cause an overflow... maybe the text is just one tiny i, or even a load of zero-width-spaces. All you can do is add the text and see if it overflows afterwards.

var hasoverflowed= div.offsetHeight<div.scrollHeight;
// more or less... modulo borders
bobince
A: 

Assuming your div is fixed height, set overflow:hidden and check the div.scrollHeightproperty.

if(myDiv.scrollHeight > myDiv.offsetHeight) { /* the div is full */ }
else { /* there is room left */ }
Rob