2
 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

M S Reddy
  • 197
  • 1
  • 4
  • 14
  • Although not exactly the same as what you are asking, I think this StackOverflow q&a has just what you are looking for: http://stackoverflow.com/questions/4934807/know-what-overflowhidden-has-hidden – pms1969 May 21 '12 at 12:17

2 Answers2

1

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.

Neji
  • 6,591
  • 5
  • 43
  • 66
1

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...

Denys Séguret
  • 372,613
  • 87
  • 782
  • 758