How to Change Font Size onClick in WordPress with JavaScript

86

Have you ever come across a site or blog that lets their visitors change the font size from some +/- button in the sidebar? Normally, you should never have to add this feature because all major browsers have the zoom in/zoom out buttons, but there are still a good number of users who are not familiar with that zoom feature. Well in this article, we will show you how to give your users the ability change the font size in WordPress using a simple JavaScript function and some HTML.

First lets add this script in your header or footer:

<script type="text/javascript">function resizeText(multiplier) {    if (document.body.style.fontSize == "") {      document.body.style.fontSize = "1.0em";    }    document.body.style.fontSize = parseFloat(document.body.style.fontSize) + (multiplier * 0.2) + "em";  }</script>

Then simply add this code anywhere in your theme (most people put it in the sidebar)

  <a href="javascript:void(0);" onclick="resizeText(1)" id="plustext">Make text bigger</a> | <a href="javascript:void(0);" onclick="resizeText(-1)" id="minustext">Make text smaller</a>  

You can also use images like +/- icons or others if you want. For all of this to be possible, you would need to specify the font-size for your html element.

Alternatively, if you want to limit the area of where the font-size would be included (for example: just your content area), then change the original javascript to be something like this:

<script type="text/javascript"> var c = document.getElementById("content"); function resizeText(multiplier) { if (c.style.fontSize == "") { c.style.fontSize = "1.0em"; } c.style.fontSize = parseFloat(c.style.fontSize) + (multiplier * 0.2) + "em"; } </script>

This means that you only the font size change in the element that has the id=”content”.

Looking for a live example? Check out Eric Wendelin’s Blog.

Source: David Walsh