views:

304

answers:

2

This is a followup to this question.

I am working on a component for the CKEditor, a tweaked version of the font drop-down menus that always display the currently selected font family / size values, no matter where they were defined, using computedStyle and consorts.

As you can see in the other question, determining the font size works cross-browser now. Now I am having trouble working with the fontFamily attribute. My generic "computed style" function returns only the full font string that was defined, e.g.

Times New Roman, Georgia, Serif

What I need, in order to match the setting against the entries in the font family dropdown, is a fixed font name of the actual font of the DOM element I am checking.

Can this be done somehow, at least for the most common web fonts?

+2  A: 

The UA picks the first font in the list that it finds installed. The fonts installed on the OS are not really a part of the DOM, so the best you can do is guess.

Azeem.Butt
You're right. Paul D. Waite presents a workaround that I'm not going to use in this case, but makes it possible to sort it out.
Pekka
+4  A: 

I don’t think there are any methods to do it directly, but Lalit Patel came up with a clever technique that creates an element with some letters in it, and guesses the font from the width of the element.

See http://www.lalit.org/lab/javascript-css-font-detect

Paul D. Waite
Yes I thought of that as well, it's a very clever idea. In my case however it's overkill, as the whole procedure would have to happen every time theuser changes the cursor position in a WYSIWYG editor.
Pekka
Ah, yes gotcha.I’m not familiar with CKEditor, but is there any way to track what styles are applied to what text? Rather than computing it whenever the cursor moves, could you record what styles are applied to the text whenever the user changes them?
Paul D. Waite
@Pekka Then you need to memoize the results of detection. And, perhaps, also test some of the common fonts upfront.
kangax