Change Font Size with JavaScript

Here is the javascript code to increase or decrease the font size on the fly, you can give control to the user to change the text size for better readability.

 
function resizeFont(multiply) {
  var sz = document.body.style.fontSize;
  if (sz =='') sz = 14; //default font size

  var size = parseFloat(sz) + (multiply * 0.2) + "px";
  document.body.style.fontSize = size;
}

Call the above function on click of any HTML element (image, anchor etc), below is the example with anchor tag:

 
+ 
- 

By using the above function, after changing the font size, if we go to another page, we will lose the changes as it is a separate page. If you want to maintain increased or decreased font size across all the pages, store the font size in the cookie and set the font size value from cookie in other pages.

 
function resizeFont(multiply) {
  var sz = document.body.style.fontSize;
  if (sz =='') sz = 14; //default font size

  var size = parseFloat(sz) + (multiply * 0.2) + "px";
  document.body.style.fontSize = size;
  SetCookie("fs",size,30); //store the size value in the cookie for 30 days
}

Modified the above function to store the font size set by the user in the cookie.
Read the cookie and set font value on the page load.

<body onload="setFont();">
---
</body>

function setFont() {
  var sz = ReadCookie('fs');
  if (sz != null && sz != '') {
     document.body.style.fontSize= sz;
  }
}


In the above code, i have used “SetCookie” and “ReadCookie” functions which i wrote here

2 Comments

Add a Comment

Your email address will not be published. Required fields are marked *