Reputation: 943
If a character is entered in a text field and the currently applied font does not support that character, a backup font is used for that character. Is it possible to tell via Javascript or some other means when this is happening? Trying to create a script which alerts the user if a certain character is not supported by the font. Thanks for your help!
Upvotes: 20
Views: 3251
Reputation: 1131
Checking the width of the character in the font, and comparing it with the fallback, you can infer if it is using the fallback font. This test is probably not 100% reliable, but you can do something like:
var text = $(".main-text").html();
var chars = text.split("");
for(var i = 0, len = chars.length; i < len; i++){
var str = chars[i]; str+=str;str+=str;str+=str;
$("#test1, #test2").html(str);
var w1 = $("#test1").width();
var w2 = $("#test2").width();
if(w1 == w2 && w1 != 0){
alert("char not supported " + chars[i]);
}
}
.main-text {
width: 50%;
height: 300px;
font-family: Impact, sans-serif;
font-size: 16px;
}
#test1, #test2 {
position: fixed;
top: -100px;
font-size: 16px;
}
#test1 {
font-family: Impact, sans-serif;
}
#test2 {
font-family: sans-serif;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<textarea class="main-text">
Serif Font
This E is not supported: ể
</textarea>
<span id="test1"></span>
<span id="test2"></span>
Upvotes: 3
Reputation: 53597
This sounds like a job for something like fontkit.js or opentype.js, or even Font.js, all of which can test fonts for glyph support. System fonts are not covered this way (Font.js might work, it'll probably report a width 0 for the tested glyph) but then these are typically the "web safe" fonts, of which we already know exactly which glyphs are supported because everyone uses the same ones. For testing "holes" in a custom font, though, any of the previously mentioned three should already do what you intended to implement.
Upvotes: 3