Font Size Changer Feature: A JavaScript Tutorial

Font Size Changer Feature: A JavaScript Tutorial

Learn How to Add Font Size Changer Buttons to Your HTML or React Website with Easy-to-Follow Steps

Have you ever felt the need for functionality where you can increase or decrease the font size of the text of your entire site with a single button click? Well, today we are gonna learn to do the same. I am going to show you how to do it in simple HTML, CSS and JS. Also, I am gonna give you instructions along the way on how you can do it on React JS. You can translate the code into your preferred frameworks. All you need is the JS logic to do so and you are good to go.

Steps

Step 1: HTML

Firstly, I am gonna create an HTML file to resemble a very basic site with a navbar that contains 3 buttons, one for each increasing, decreasing and resetting the font size of the site, and some text on the body.

<!DOCTYPE html>
<head>
    <title>Font inc dec demo</title>
</head>
<body>
    <Navbar class='nav'>
        <button id="dec" class='btn'>A-</button> 
        <!-- for decreasing font -->
        <button id="res" class='btn'>A</button> 
        <!-- for resetting font -->
        <button id="inc" class='btn'>A+</button>        
        <!-- for increasing font -->
    </Navbar>
    <main class='main'>
        <h1>Welcome</h1>
        <p>Lorem ipsum dolor sit amet consectetur ............</p>
        <br>
        <h2>About Us</h2>
        <p>Lorem ipsum dolor sit amet consectetur ............</p>
        <br>
        <h3>Have a good day</h3>
    </main>
</body>
</html>

Step 2: CSS

Now let's add some styling to our site. I will add very basic styling here. My main motive is to show you the JS logic. You can skip this as it is not very important.

:root {
    font-size: 16px;
}
* {
    padding: 0;
    margin: 0;
}
.nav {
    display: flex;
    flex-direction: row;
    background-color: rgb(179, 185, 185);
    height: 56px;
    width: 100%;
    align-items: center;
    justify-content: center;
}
.btn {
    margin: 0px 16px;
    padding: 8px;
    width: 36px;
    font-size: 16px;
}
.main {
    padding: 24px 88px;
    text-align: center;
}

Note: It is important to notice that I have not given font size to the main text because the CSS given here always tends to have priority over the JS logic.

Step 3: JS logic

Now we will write the main JS logic here.

Firstly we will write and understand the logic for decreasing the font.

const decreaseFontSize = () => {
  // Get current font size
  let currentFontSize = parseInt(
    getComputedStyle(document.documentElement).fontSize
  )

  // Decrease font size by 1 pixels, but don't go below 8 pixels
  let newFontSize = Math.max(currentFontSize - 1, 8)

  document.documentElement.style.fontSize = newFontSize + 'px'
}

In this code, we're using the getComputedStyle method, which is a built-in JavaScript function that returns the computed style for a given element. In this case, we're passing in document.documentElement, which refers to the root element of the HTML document, i.e., the <html> element.

By passing in the root element, we're essentially asking the browser to return the computed styles for the entire page. Then, we're accessing the fontSize property of the computed style object to retrieve the font size of the root element. Finally, we are storing it in a variable named currentFontSize.

Then, the next block of code is reducing the currentFontSize by 1 pixel, but ensuring that it won't be set to a value smaller than 8 pixels using Math.max() and assigning it to newFontSize.

Finally, we are accessing the style property of the root element of the HTML document, which is referred to as document.documentElement. The style property is an object that represents the inline style of an HTML element. In this case, we're accessing the fontSize property of the style object, which represents the font size of the root element. By accessing the fontSize property in this way, we can get or set the font size of the root element dynamically using JavaScript which is exactly what we are doing above.

Now here is the code of the remaining functions.

const decreaseFontSize = () => {
  // Get current font size
  let currentFontSize = parseInt(
    getComputedStyle(document.documentElement).fontSize
  )

  // Decrease font size by 1 pixels, but don't go below 8 pixels
  let newFontSize = Math.max(currentFontSize - 1, 8)

  document.documentElement.style.fontSize = newFontSize + 'px'
}

const increaseFontSize = () => {
  // Get current font size
  let currentFontSize = parseInt(
    getComputedStyle(document.documentElement).fontSize
  )

  // Increase font size by 1 pixels, but don't go above 24 pixels
  let newFontSize = Math.min(currentFontSize + 1, 24)

  document.documentElement.style.fontSize = newFontSize + 'px'
}

const resetFontSize = () => {
  // Set font size to default value (16px)
  document.documentElement.style.fontSize = '16px'
}

Now let's target each button using their id and assign a click event listener to them so that a specific function gets run when the user clicks on the button.

let decBtn = document.getElementById('dec')
decBtn.addEventListener('click', decreaseFontSize)

let incBtn = document.getElementById('inc')
incBtn.addEventListener('click', increaseFontSize)

let resBtn = document.getElementById('res')
resBtn.addEventListener('click', resetFontSize)

And also don't forget to import both the CSS file and JS file to the HTML file.

Whole JS file

const decreaseFontSize = () => {
    console.log('decreadinngggg............')
  // Get current font size
  let currentFontSize = parseInt(
    getComputedStyle(document.documentElement).fontSize
  )

  // Decrease font size by 1 pixels, but don't go below 8 pixels
  let newFontSize = Math.max(currentFontSize - 1, 8)

  document.documentElement.style.fontSize = newFontSize + 'px'
}

const increaseFontSize = () => {
  // Get current font size
  let currentFontSize = parseInt(
    getComputedStyle(document.documentElement).fontSize
  )

  // Increase font size by 1 pixels, but don't go above 24 pixels
  let newFontSize = Math.min(currentFontSize + 1, 24)

  document.documentElement.style.fontSize = newFontSize + 'px'
}

const resetFontSize = () => {
  // Set font size to default value (16px)
  document.documentElement.style.fontSize = '16px'
}

let decBtn = document.getElementById('dec')
decBtn.addEventListener('click', decreaseFontSize)

let incBtn = document.getElementById('inc')
incBtn.addEventListener('click', increaseFontSize)

let resBtn = document.getElementById('res')
resBtn.addEventListener('click', resetFontSize)

Points to be noted

  1. While importing the JS file, use defer attribute if you are importing the JS file inside the head tag.

     <script src="logic.js" defer></script>
    
  2. Don't set any font size on any elements as it gets priority in styling over the JS logic. Hence your function will not work. Instead, you can set the font size of the root element and then use heading tags like h1, h2, and h3 for the sizing of the texts.

React JS guide

You can pretty much figure out how to do it in react by now. Still, I am gonna provide you with the guides.

Steps

  1. Firstly, create a JS file with the functions I mentioned above. Also, don't forget to export them.

    (You can copy the code below......scroll down a bit for whole JS file......)

  2. Import the file into your component or page.

     import { decreaseFontSize, increaseFontSize, resetFontSize } from '@utils/fontIncDec';
    
  3. Add the onClick event Handler in the buttons with the specific function assigned to it like this:

     <div>
         <button onClick={decreaseFontSize}>A-</button>
         <button onClick={resetFontSize}>A </button>
         <button onClick={increaseFontSize}>A+</button>
     </div>
    
  4. Voila! You're done.

Whole JS file (for React)

export const decreaseFontSize = () => {
  // Get current font size
  let currentFontSize = parseInt(
    getComputedStyle(document.documentElement).fontSize,
  );

  // Decrease font size by 1 pixels, but don't go below 14 pixels
  let newFontSize = Math.max(currentFontSize - 1, 14);

  document.documentElement.style.fontSize = newFontSize + 'px';
};

export const increaseFontSize = () => {
  // Get current font size
  let currentFontSize = parseInt(
    getComputedStyle(document.documentElement).fontSize,
  );

  // Increase font size by 1 pixels, but don't go above 18 pixels
  let newFontSize = Math.min(currentFontSize + 1, 18);

  document.documentElement.style.fontSize = newFontSize + 'px';
};

export const resetFontSize = () => {
  // Set font size to default value (16px)
  document.documentElement.style.fontSize = '16px';
};

Notes

Don't use font size on specific elements on your site as it has precedence over the styles from JS logic.

Github link: Click here

Finally, if you have anything, feel free to comment or DM me on any social links you can find. You can visit my site for that too. Click here to get to my site.

Happy Coding!