M S Reddy
M S Reddy

Reputation: 196

Find a text length which is display in div element that has overflow hidden

 some text is here in div element like this 

div{ width:100px; overflow:hidden;height:20px;}

Now, i want to get length of visible text only,Not entire text of div element.

How can i achieve this ...

Thanks

Upvotes: 2

Views: 1008

Answers (2)

Denys Séguret
Denys Séguret

Reputation: 382092

I found this problem funny, so I devised a way to effectively measure the length in characters of the visible text.

You can test it there : http://jsfiddle.net/6nYFb/

The idea is to iteratively fill the text until the 100px width is attained.

CSS :

#txt{ max-width:100px; overflow:hidden;height:20px;}​

HTML :

<span id=txt>My long text is long. My long text.My long text. My long text... My long text. My long text, so long...</span>
<br>Nb chars : <span id=mes></span>​

JS :

var text = $('#txt').text();
var nbchars = 0;
$('#txt').html('');
var increment = function() {
    $('#txt').html(text.substring(0, nbchars));
    if (nbchars<text.length-1 && $('#txt').width()<100) {
        nbchars++;
        window.setTimeout(increment, 1);
    } else {
        $('#mes').html(nbchars);
    }
};
window.setTimeout(increment, 1);

Of course, it's better not overusing this kind of solution, but I don't see anything more direct without canvas. And it works.

Another (less compatible) solution could be to use a in memory canvas instead of modifying the DOM but some text transformation (or :before) defined in css could be hard to reproduce...

Upvotes: 1

Neji
Neji

Reputation: 6839

why dont you limit your textbox to no. of characters entered. you visit a demo where you can check the no. of characters entered and put a limit click here same function you can impliment and use it for your purpose.

Upvotes: 1

Related Questions