jQuery Font Resizer

See the Pen Font Resizer by James (@jamcgrath) on CodePen.

On my last project I was required to make a font resizing function that enlarges or decreases the global font size. It’s pretty easy to change the font size in jQuery. You could use something like this.

$(".selector").on("click", function() {
  $("html").css("font-size", "125%");
});

However binding the font resize to a click event only works for the current page and will be reset when the user goes to another page. To make it stay persistent I opted to use the HTML5 session storage to set a variable that gets checked on page load and sets the font size.

// change font size and set session storage variable
function changeFont(fontSize) {
  return function() {
    $("html").css("font-size", fontSize + "%");
    sessionStorage.setItem("fSize", fontSize);
  };
}

//check to see if session storage is set
if (sessionStorage.length !== 0) {
  $("html").css("font-size", sessionStorage.getItem("fSize") + "%");
}

I think overall the code is pretty self explanatory. if you have not seen the following before, it’s the equivalent of

$(document).ready(). The style below is useful for using $ in WordPress instead of having to write jQuery before everything.

(function($) {
  //do stuff
})(jQuery);
comments powered by Disqus