JavaScript: How to allow users to change the font-size of a webpage?

JavascriptWeb DevelopmentFront End Technology

In this article, we are going to explore creating a function that will allow the user to change the font size of the complete webpage. We can generally see this type of feature on some of the government websites in the top right corner. This is basically to facilitate people using the website to enlarge the web content as required.

In this article ,we will be applying the same function using JavaScript & JQuery

Example #1

In the below example, we have created a simple div program and created two buttons i.e. Increase and Decrease. We have used these 2 functions to increase the font of the div and the decrease button for decreasing the div font.

#Filename: index.html

<!DOCTYPE html>
<html lang="en">
<head>
   <title>Change Font Size</title>
   <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.2/jquery.min.js"></script>
</head>
<body>
   <center>
      <h1 style="color: green">
         Welcome To Tutorials Point
      </h1>
      <button type="button" value="increase" class="increaseFont">
         Increase Font ++
      </button>
      <button type="button" value="decrease" class="decreaseFont">
         Decrease Font --
      </button>
      <div style="padding: 20px; margin: 50px;
         font-size: 20px; border: 5px solid red;"
         id="container" class="data">
         Tutorials Point originated from the idea that there exists a class of readers who   respond better to online content and prefer to   learn new skills at their own pace from the   comforts of their drawing   rooms.
         The journey commenced with a single tutorial on HTML in 2006 and elated by the response it generated, we worked our way to adding fresh tutorials to our repository which now proudly flaunts a wealth of tutorials and allied articles on topics ranging from programming languages to web designing to academics and much more.
      </div>
   </center>
   <script type="text/javascript">
      $(document).ready(function(){
         $(".increaseFont,.decreaseFont").click(function(){
            var type= $(this).val();
            var curFontSize = $('.data').css('font-size');
            if(type=='increase'){
               $('.data').css('font-size', parseInt(curFontSize)+1);
            } else{
               $('.data').css('font-size', parseInt(curFontSize)-1);
            }
            // alert($('.data').css('font-size'));
         });
      });
   </script>
</body>
</html>

Output

To increase the font size click the “Increase Font ++” button and to decrease the font size click the “Decrease Font --” button.

raja
Updated on 25-Apr-2022 11:27:11

Advertisements