Apple's MobileMe uses javascript to change the font size in the email login on its homepage as the user types so that the text always fits in the available space without overflow scrolling.
While I can see how how to execute a function on each keypress, I'm curious how one would go about caluclating the font-size each time so that it always fits into the input field. Is there a way to measure the length of a piece of text with a variable width font? How do they accomplish this effect?
Try it out to see what I mean: http://www.me.com/
I made another one from a hodgepodge of other answers. I think this provides the simplest one-property-change solution.
It's likely overly verbose or could be refactored for clarity in some ways, any suggestions welcomed!
I've done this in the past using jQuery. You can measure the size of a piece of text like this:
In order to fit this to a given space, it's a little trickier - you need to separate out the
font-size
declaration and scale it appropriately. Depending on how you're doing things, this might be easiest if you break out the different parts of thefont
declaration. A resize function might look like this (again, obviously, this is jQuery-dependent):You can see this in action here: http://jsfiddle.net/nrabinowitz/9BFQ8/5/
Testing seems to show that this is a little jumpy, at least in Google Chrome, because only full-integer font sizes are used. You might be able to do better with a
em
-based font declaration, though this might be a little tricky - you'd need to ensure that the1em
size for the text width tester is the same as that for the input.