JavaScript Change Text Size

Table of Contents

TL;DR: Here is a code snippet that you can use to change the text size. There is a full application in the post going over how this can be used.

document.getElementById("id").style.fontSize = 20px;

In this post we are going to create a pretty neat application. We are going to implement a slider, where when we slide it we will increase or decrease the size of some text.

In order to change the font size using Js we are going to work with the style property, just like what you see in the code snippet above.

What we will need for our text size application

There are a few things that we need for our application. We are not going to add any fancy styling, but we need the following:

  1. The slider
  2. Some text that we will increase
  3. The JavaScript code

That is it. You will see that we will be able to increase and decrease the text size using JavaScript without too much code. Most of the code will actually be related to getting the input from the slider and setting things up.

Adding our slider

You can style your slider a lot of you want but for this example we are just going to go with the default one, which still looks pretty good on my opinion.

<input type="range" min="10" max="20" value="10" id="textSizeSlider">

We are also going to add just a little bit of CSS so that the slider does not take up the whole width of the page. This CSS will be inside style tags when I embed the application at the bottom of this page.

#textSize{
    width:100px;
}

Here is what the slider will look like. This one does not do anything but slide back and forth.

Adding our text

The text that we will increase the size of using JavaScript will just be inside a simple <p> tag. We will add an id to this tag just so that it is easier for us to get a hold on it with JS. Depending on your situation, you might have to do something similar with your application. It comes down to your use case.

<p id="textToIncrease">How to increase text size using JavaScript<p>

Adding our JavaScript code

The last thing that we need for our application is the JavaScript code that will do our logic for us. The slider goes from 10 to 20, this will represent the pixel size of the text. Each time we get the value from the slider we will increase the size of the text using the style property.

var ourSlider = document.getElementById("textSizeSlider");
var text = document.getElementById("textToIncrease");

ourSlider.oninput = function(){
    text.style.fontSize = this.value + "px";
}

How to increase text size using JavaScript

That is is it for this application. It is a pretty fun one, and you should try to implement your own where you use different values and a different text type than a paragraph. Try using a header tag for example.

If you want to learn more about JS then check out our post on how to get the current time and how to get input using JavaScript.

Related Guides