It happens that sometimes the font size on a page is so small that its unreadable and sometimes annoyingly large. Agree that browsers provide the feature to increase or reduce font size of a page, how many actually know it?
Lets create an example in which user will be able to increase/reduce font-size at his will.
If you want to have a look at source code, you can always do so by doing view source on your browser.
Create a html page with the following markup:
<p id="content" style="font-size:12px;">
My name is Sherlock Holmes. It is my business to know
what other people don't know.
This page contains a p tag with id set to content with some text inside it. Note that the font-size property has been set for content as 12px inline.
For increasing font I have passed 2 to it, and for the decrease font button the value is -2. Each time any of the links is clicked, it will increase or reduce the font size by 2px. Change this value to what suits you.
Now we will add the definitions for function changeFontSize. Insert the following code between script tags in the head of your html page.
step = parseInt(step,10);
var el = document.getElementById(element);
var curFont = parseInt(el.style.fontSize,10);
el.style.fontSize = (curFont+step) + 'px';
In fact, you can squeeze above 4 lines into a single line:
document.getElementById(element).style.fontSize = (parseInt(document.getElementById(element).style.fontSize,10) + parseInt(step,10)) + 'px';
Use whichever you prefer.
Now you are done. Refresh the page and click on Increase Font/Decrease Font links.Font size will change accordingly.
How does this happen actually?
- First convert step as an integer
- Then use the style property to get the font size that has been set for the element. element.style.fontSize will give us 10px. Pass it to function parseInt to get an integer value – 12 in this case.
- Finally reset the fontSize property for the element by adding the value of step.
There may be other methods/variations also by which you can control the font size. For example, create a combo box with values for font size as smaller,small,medium,large and largest.Each value of combo box will have a specific font size associated with it say 8px,10px,12px,14px and 16px respectively. Onchange event will set the font size according to selected value.
Thats all. Hope you enjoyed the post.