Tony
Tony

Reputation: 12705

How to check if the string size is greater thatn its container's size?

in my div of the size e.g 100x200px, I have a html-formatted string. I want to limit the count of displayed character's of that string, if the string size (or length?) is grater that this div size (then I want to use tooltip). Any ideas how to do that ? I could convert that string to the plain version and then check the size, but is it a good idea ?


I've found that article to check:

http://blog.mastykarz.nl/measuring-the-length-of-a-string-in-pixels-using-javascript/


I've noticed the another problem, the string trimming seems to be working, but, I'd like to view the trimmed string saving its html tags

Upvotes: 0

Views: 375

Answers (2)

reiti.net
reiti.net

Reputation: 33

You can put the string in another (hidden) element like a span, disable wrapping in style - in script you can get the width of this span and can compare if it is bigger than your div.

Dont forget to set appropriate styles like white-space:nowrap

For limiting the fixed size field you can just set overflow:hidden (you have to set overflow:visible on the invisible span). This way, the characters get cut off and the users maybe see, that there is more text.

Upvotes: 2

Grim...
Grim...

Reputation: 16953

Create an identical div (but with no scroll restrictions) with the string inside somewhere off the page where the user cannot see it, and check the size of that.

Then loop through the string while removing a few characters at a time until it fits.

Upvotes: 2

Related Questions