views:

560

answers:

3

I need to write in javascript (jquery) a function that is aware of the number of characters that fit in a line of the browser window. I'm using a monospace font to ease the problem, but it would be better if I generalize it for different fonts.

How can I know how many characters would fill a row in the browser?

The intention is to count the number of characters that fill a line.

Thanks.

+1  A: 

You can get the total width available for the browser with

window.innerWidth

And then you can get the width of an element with the following method.

document.getElemenById('elem').clientWidth
Boris Guéry
This would work for monospace fonts (windowWidth/elementWidth), right?
alvatar
It doesn't care, it just return the witdh of element.It may not be the solution, but it could give you some hints to do..
Boris Guéry
+1  A: 

There is no easy way to do this in HTML.

However, if you really must know, you can probably figure it out with some really ugly javascript:

First, create a <div> with the width you need, put some characters in and request its .height() in pixels. Then, keep adding characters to it and keep checking the .height(), when the height of the <div> changes you know it has grown to fit a new line of text.

warpr
Yeah, it seems this is the way. Ugly, but if it works... :D
alvatar
What happens when the browser is resized? If you were to recalculate this every time the user changes page or resizes the page, this will be a huge strain on their resources
Perspx
+3  A: 

You can create element and append characters to it until you detect wrapping, e.g. by observing changes in offsetHeight (you can optimze it using bisection algorithm).

This is of course very dependent on browser, system, installed fonts and user's settings so you would have to calculate it for each fragment of text each time page is displayed, resized or when user changes font size (even full-page zoom introduces some off-by-one errors which could cause number of characters change).

Therefore it may be an overkill in most situations and when implemented poorly cause more trouble than it solves.

There are other solutions, e.g. if you want to ensure that only one line is visible you can use white-space:nowrap and overflow:hidden and in some browsers text-overflow:ellipsis to make text cut nicely. Or if you don't want words cut, use 1-line high container with overflow:hidden.

porneL
Thanks, some good suggestions here which I didn't think about :)
warpr