Easy Java Script Code to Let Your Web site Visitors Set Font Size
Why should you let visitors to your Web site set the font size? According to the U.S.
Census Bureau, adults 50 plus will grow to over 106 million by 2015, when they will account
for 45 percent of the adult population. Not only is the population aging, but adults 50 plus
are also the fastest growing segment on the Internet. If your Web site is directed toward
seniors, or people with visual impairment, giving your Visitors a way to set the font size is crucial.
In this article, you'll learn that it requires only a few lines of Java Script to let
the visitors to your Web site control the font size. You'll also learn how to use a cookie
to store their preference on their computer. You'll also learn how to set the cookie so that
their one time font size preference will apply to every page on your website, and when they
leave your Web site, they won't have to set it again when they return.
• Before you proceed, consider what impact changing the font size may
have on your webpage layout. In some cases, this may cause your layout to stretch and distort.
You may need to go back and set absolute dimensions for some elements.
The first step is to add the attributes shown below to the <body> tag of your webpage.
<body id="myBody" onLoad="setFont();">
The first attribute assigns an id to the body element. This will also work with
other webpage elements like a div, span, or table. The second attribute makes
the onLoad event of the body tag execute a function named setFont.
This function will be used to set the initial font size every time a webpage loads. The
code for the setFont function is shown below. Paste this Java Script code block
into the <head> section of your webpage.
var sizeFont = "=12px";
var setSize = sizeFont;
setSize.substring( setSize.indexOf("=") + 1, setSize.indexOf("x") + 1 );
This code creates a global variable named sizeFont and initializes it to
the string value "=12px". The setFont function creates a variable named setSize
and initializes it with the value in sizeFont. It then uses the String object's
substring method to extract the substring "12px" from setSize, and uses
the document's getElementById method to set the size of the font.
The second step is to place the two links shown below at the top of the <body>
section of your webpage.
• You could get fancy and make these links into styled buttons or graphic image buttons.