Simple Text Resizing using JavaScript

In This article i will tell you how how you can give your site’s visitors the possibility to see your page’s content at different text sizes, using javascript. It is good for website accessibility.
You can Check Working Demo here.

Javascript Code:

Copy below Javascript code into your JS file or web page before </header>.

<script type="text/javascript">
//Specify affected tags. Add or remove from list:
var tgs = new Array( 'div','td','tr');

//Specify spectrum of different font sizes:
var szs = new Array( 'xx-small','x-small','small','medium','large','x-large','xx-large' );
var startSz = 2;

function ts( trgt,inc ) {
if (!document.getElementById) return
var d = document,cEl = null,sz = startSz,i,j,cTags;

sz += inc;
if ( sz < 0 ) sz = 0;
if ( sz > 6 ) sz = 6;
startSz = sz;

if (!( cEl = d.getElementById( trgt ) ) ) cEl = d.getElementsByTagName( trgt )[ 0 ];

cEl.style.fontSize = szs[ sz ];

for ( i = 0 ; i < tgs.length ; i++ ) {
cTags = cEl.getElementsByTagName( tgs[ i ] );
for ( j = 0 ; j < cTags.length ; j++ ) cTags[ j ].style.fontSize = szs[ sz ];
}
}
</script>

Resizing Controls

Next add below code into your web page, Where you want to put controls for text resizing. you can use icons or images as per your design requirement.
<a href="javascript:ts('body',2)">+ larger font</a> | <a href="javascript:ts('body',-1)">- Smaller font</a>

Download Example

1 comment

Comments are closed.