Css / Wordpress

How to Change Font Size onClick in WordPress with JavaScript

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:

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

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

1 <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:

1 <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”.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s