Home

SiteMap

How to change font-size with range input using JavaScript

← PrevNext →

Here's another JS quick tip. You can change the font-size of a text in your webpage dynamically with range input using JavaScript. I'll show two simple methods to do this.

change font-size of a text with range input using javascript

Let us assume, I have a <p> element with some content in it (you can use any other element). I also have a range input element. When I drag or slide the range, the JS script should take the value of the range and use the value to set the font-size of the element (any element, it can a textbox or a textarea etc.).

Method 1

In this method, the oninput attribute will call a function (a User Defined Function) while dragging or sliding the range. The function takes an argument as size.

<body>
  <input type="range" id="theRange" 
    min="0" max="72" 
    value = '18'
    oninput=
       "document.getElementById('fontsize').innerHTML = this.value + 'px'; 
       changeFontSize(this.value); " />
  
  <label id="fontsize"></label>

  <p id='txt'>Hello, I am Arun Banik</p>
</body>

<script>
  const changeFontSize = (size) => {
    document.getElementById('txt').setAttribute('style', 'font-size: ' + size + 'px');
  }
</script>
Try it

Using the setAttribute() method, I can set a new font-size (or any other property) to an element.

Method 2

Here in this method, I am using an event listener to listen to any change that occurs while sliding or dragging the range element.

<body>
  <input type="range" id="theRange" 
    min="0" max="72" 
    value = '18'
    oninput="document.getElementById('fontsize').innerHTML = this.value + 'px'; " />
  
  <label id="fontsize"></label>

  <p id='txt'>Hello, I am Arun Banik</p>
</body>

<script>
  const range = document.getElementById('theRange');
    
  range.addEventListener('input', function() {
    document.getElementById('txt').setAttribute('style', 'font-size: ' + this.value + 'px;');
  });
</script>
Try it

You can use any of the above two methods. 🙂

← PreviousNext →