Oct 31, 2023

f Comment

How To Use Javascript To Make HTML Body Font Bigger or Smaller?

Amazon How do you incrementally increase or decrease HTML body font size via Javascript, perhaps with two buttons, one for increasing and one for decreasing the font size?

Many tutorials teach you how to make the body font bigger or smaller, but not incrementally. You'd like to continually make the HTML font bigger by clicking some button multilpe times, which may be labled A+. Also, you'd like to continually make the HTML font smaller by clicking some button multilpe times, which may be labled A-.

My tutorial will teach you to gradually increase/decrease the font size with a click of a button.

Here's how. Let's assume you are using 'px' as the unit for your HTML body font via CSS.

Javascript Code to Increase Font Size

document.body.style.fontSize = parseInt(window.getComputedStyle(document.body, null).getPropertyValue('font-size'))+2+'px';


Javascript Code to Decrease Font Size

document.body.style.fontSize = parseInt(window.getComputedStyle(document.body, null).getPropertyValue('font-size'))-2+'px';


The code should be quite self explanatory. You can change the number "2" to any other number you want. If you use another unit for the font size attribute in CSS such as 'em', 'rem', and '%', change 'px' accordingly. You can even change 'document.body' to another HTML element.

Questions? Let me know!
Please leave a comment here!
One Minute Information - by Michael Wen
ADVERTISING WITH US - Direct your advertising requests to Michael