Monday, February 3, 2014

How to display a preview of CSS fonts in a Select Option drop down menu

The HTML Select Option element is normally used to display a list of options for users to make a choice. I wanted to use the option list for users to choose a font to use for further processing. I thought it would be nice to be able to show a preview of the fonts in the list itself, like how word processing software like Microsoft Word does it. I managed to figure how to do it by using some web fonts from Google, cascading style sheets (CSS) and a Web Font Loader.

In general, the following needs to be done in the HTML page: (1) download the web fonts you want to use in the select option list, (2) define style sheet classes for each font,  and (3) wrap each option with the optgroup tag and assign it with the style sheet class.

I managed to get this to work for Chrome and FireFox browsers but not for any of Microsoft's Internet Explorer browsers.

Download web fonts
In the header head tag section of the HTML file, make a link using the link tag to the web fonts you want to use. An example is shown below. Here, I am linking to the Allura and Dynalight fonts from Google.


<!DOCTYPE html> 
<html> 
<head> 
<title>Example font preview</title> 
<meta name="viewport"
content="width=device-width, initial-scale=1.0, user-scalable=no"> 
<meta charset="UTF-8"> 
<link href="../webappstyles.css" rel="stylesheet" type="text/css" />
<link href='http://fonts.googleapis.com/css?family=Allura' rel='stylesheet' type='text/css'>
<link href='http://fonts.googleapis.com/css?family=Dynalight' rel='stylesheet' type='text/css'>        


If you want to use the fonts in Javascript, then it would be wise to use the Web Font Loader to pre-load the fonts. This can be done by appending the font family names to the Web Font load method. The example code shows how this is done. The code can be included in the HTML head tag section.


<script src="//ajax.googleapis.com/ajax/libs/webfont/1.4.7/webfont.js"></script>
<script>
WebFont.load({
google: {
families: ['Allura', 'Dynalight']
}
});
</script>    


Define CSS classes
Inside the style tag section of the header, define a style sheet class for each font you want to use.


<style type="text/css">
.Allura { font-family: Allura, cursive; }
.Dynalight { font-family: Dynalight, cursive; }    
</style>

Wrap each option
In the select tag, wrap each option tag with the optgroup tag and assign the appropriate CSS style defined previously.


<select id="fontTypeCombo">
<optgroup class='Allura'>
<option>Allura</option>
</optgroup>
<optgroup class='Dynalight'>
<option>Dynalight</option>
</optgroup>
</select>

Now, when the HTML page is displayed in Chrome or FireFox, clicking on the select option combo box should display a list with a preview of the fonts.

No comments: