How To Make Text Bigger Or Smaller Automatically Using Javascript Jquery For Accessibility Purposes?

How To Make Text Bigger Or Smaller Automatically Using Javascript Jquery For Accessibility Purposes?

If you need or would like accessibility functions on your website for the visually impaired – using JavaScript and the jQuery library is the easiest way to go about it.

While the demonstration in this article works, it does not remember any settings across different pages which you can add easily by setting a cookie that remembers any accessibility settings that the end user applies – it would definitely save them having to set the text bigger each time they go to a different page on your website.

Luckily, this is very easy in jQuery with a jQuery Cookie plugin available via GitHub. Setting a cookie using the plugin is really easy:

...

<script src="/src/to/jquery/plugin.js"></script> <!-- include the jQuery plugin -->

...

$.cookie('cookie_name', 'cookie_value', { expires: 14 }); // expires in 14 days

document.write($.cookie('cookie_name')) // outputs the cookie value

How do I change the size of text on the web page using jQuery?

To change the size of text in an HTML element using jQuery in an animating effect (so it gradually increases), you can make use of the animate() method in jQuery like follows:

$(document).ready(function()
{
  $('#t_bigger').click(function()
  {
    var curr_font_size = $('#content p').css('font-size');
    var new_font_size = parseFloat(curr_font_size) + 3;
    $('#content p').animate({fontSize: new_font_size}, 250);
  });

  $('#t_smaller').click(function()
  {
    var curr_font_size = $('#content p').css('font-size');
    var new_font_size = parseFloat(curr_font_size) - 3;
    $('#content p').animate({fontSize: new_font_size}, 250);
  });
});

What does parseFloat() do?

Because the font-size will be a numeric value with the measurement unit (e.g., px, em, etc.), the parseFloat() parses a string and returns a floating point number, so in 22px – parseFloat() will return 22.

General explanation

In essence, when the the “t_smaller” or “t_biger” div is clicked (which may contain a “T” icon image, for example), the current font-size is fetched and an extra 3 pixels (or whatever measurement unit you are using) is added onto, or subtracted from, the new font-size that is set using the animate() method.

And because the animate() method is used to set the new font size, it sets the new font size gradually – like an animation. The duration is set for milliseconds. So the animation duration is 250 milliseconds in the jQuery examples above.

Sharing