Simple method to modify the text size of the entire HTML page

Looking for a way to adjust the font size of an entire HTML document?

I'd like to have two buttons - one to increase the font size and the other to decrease it. Each button will trigger a JavaScript function;

function increaseFontSize(){
//Increase the font size of the entire document
}

function decreaseFontSize(){
//Decrease the font size of the entire document
}

Inquiry

How can I achieve this? Is there a simpler method than the one mentioned above?

Update:

Currently using Bootstrap, which has its own CSS styles for each HTML element. The default font size set by Bootstrap is 14px.

Answer №1

To adjust the font size of the HTML element, you must first ensure that there is an initial value set for easy modification.

You can achieve this by executing the following code:

document.getElementsByTagName("html")[0].style["font-size"] = "10px";

Once the initial value is in place, you can then implement incremental changes to the font size using the function below:

function increaseFontSize() {
    var currentSize = document.getElementsByTagName("html")[0].style["font-size"];
    var intValue = parseInt(currentSize.replace("px", ""));
    intValue += 10;
    document.getElementsByTagName("html")[0].style["font-size"] = intValue + "px";
}

To enhance the readability and maintainability of the code, consider utilizing helper functions like the examples provided below:

function extractCurrentSize() {
    var existingSize = document.getElementsByTagName("html")[0].style["font-size"];
    return parseInt(existingSize.replace("px", ""));
}

function increaseFontSize() {
    var currentValue = extractCurrentSize();
    currentValue += 10;
    document.getElementsByTagName("html")[0].style["font-size"] = currentValue + "px";
}

Answer №2

One approach is to utilize em units in your CSS and incorporate Jquery to achieve the desired solution.

You can establish a universal value for the body element and then modify it accordingly:

$(document).ready(function(){
    var fontSize = parseInt($('body').css('font-size'),10);
    $('.inc').on('click',function(){
        fontSize+=0.5;
        $('body').css('font-size',fontSize+'px');
    })
    $('.dec').on('click',function(){
        fontSize-=0.5;
        $('body').css('font-size',fontSize+'px');
    })
})
body {
    font-size:12px;
    padding-top:20px;
}
.tit {
    font-size:3em;
}
.sub {
    font-size:2em;
}
.cont {
    font-size:1em;
}
.button {
    position:absolute;
    top:0;
    font-size:15px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<div class="tit">Main Title</div>
<div class="sub">Subtitle</div>
<div class="cont">Contents</div>
<div class="button">
    <a class="inc" href="#">Increase</a>
    <a class="dec" href="#">Decrease</a>
</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is it possible for ng-model to verify its own value?

Recently, I've been experimenting with Angular and found myself facing a dilemma. Is it possible to apply a different CSS style based on whether the value of ng-model is greater than 0? `<span ng-model="users2" ng-hide="!myVar" ng-class="{'te ...

Iterating through an object using the forEach method (uncommon practice)

Greetings, I have the following object: data = { name: undefined, age: undefined, gender: undefined }; I am looking to iterate through each key and value pair in this object and perform an action. Here is my attempt: this.data.forEach((item: ...

Obtain the Row ID for Updating without Redirecting

A table in PHP/MySQL has been created with an edit button linked to each row. When the Edit button is clicked, it redirects to the same page but with the ID of the corresponding row item. This helps the PHP script retrieve the ID of the selected item. < ...

Convert XML to an HTML table in real-time as new elements are introduced

Currently, I have JSON and AJAX code that fetches XML data every second, which is working smoothly. When I added an XML element, it automatically gets added to an HTML table. The issue arises when I call the function every 3 seconds; the page refreshes due ...

Separate string by using a regular expression pattern

Looking to parse a dynamic string with varying combinations of Code, Name, and EffectDate. It could be in the format below with all three properties or just pairs like Code-Name, Code-EffectDate, or Name-EffectDate. {"Code":{"value":"1"},"Name":{"value": ...

Is it possible for Angular2 to map a lone JSON object?

Dealing with a JSON response that is a single object, rather than an array, can be tricky. Recently in my project, I encountered a situation where I needed to map and use such a response from an API to fill out a template. It seemed like a simple task at f ...

Executing a Drupal rule using JavaScript: A step-by-step guide

I'm facing a challenge when trying to activate a Drupal rule using JavaScript code. lowerLayer[image.feature_nid].on("dragend", function() { var position = kineticImage.getPosition(); var layerPosition = this.getPo ...

The Navbar in Bootstrap 3 remains expanded and does not collapse

It seems like there's a simple solution I'm overlooking. When I resize my screen, the navbar collapse toggle stops working. I've searched various forums but couldn't find a fix that works for me. Could someone lend a hand in identifyin ...

show information from json onto an html page with the help of jquery

I'm looking to showcase buttons from a JSON file within a simple block. Here's the JSON data for movies: { "movies": [ { "title": "Mena", "movieid": "1", ...

What is the best approach to resolving the MongoServerError: E11000 duplicate key error?

Index.Js File: const cookieSession = require("cookie-session"); const express = require("express"); const app = express(); const helmet = require("helmet"); const morgan = require("morgan"); const dotenv = require(&q ...

Trigger animation once you've scrolled past a designated point in the document

I created a count-up counter animation using JavaScript, but the issue is that the counter starts animating as soon as I refresh the page regardless of where I am on the page or if the counter is even visible. I would like the counter to only start workin ...

Sending back JSON arrays containing Date data types for Google Charts

One of my challenges involves using a 'Timelines' chart from Google Charts, which requires a JavaScript Date type when populating data. Here is my initial code snippet: var container = document.getElementById('divChart1'); var chart = ...

Delegating events after removing a class

I have a button element with the 'next' data attribute <button data-button='next' class="disabled">next</button> When I remove the disabled class to activate it, the click event doesn't trigger as expected $("[dat ...

Best Way to Eliminate "#" Symbol from URL Address in UI-Router

My website URL is structured as follows: This is the index page where I utilize Angular UI-Router to navigate to different views, however, the URL retains the hash symbol (#) like this: Query: I am looking for a way to eliminate/remove the hash tag from ...

Encountering Issues with Ajax Request in the Google Play App

I am facing an issue with my Phonegap app. It functions perfectly in debug mode and when installed as an apk file from Phonegap. However, when I upload it to Google Play Store and then download it from there, my ajax requests stop working. I have added the ...

Angularv9 - mat-error: Issue with rendering interpolated string value

I have been working on implementing date validation for matDatepicker and have run into an issue where the error messages do not show up when the start date is set to be greater than the end date. The error messages are supposed to be displayed using inter ...

What is the best way to serve individual static files in Express without revealing the entire "/static" directory?

For my new project, I am working on a simple setup that involves using JWT for authorization. The project is being served entirely through express, with no separation between frontend and backend. My goal is to dynamically serve specific HTML files based o ...

What could be causing the 500 internal server error when using jquery ajax with Python Bottle?

I am encountering a server 500 error while attempting an AJAX post. The python code appears to be error-free, so the issue likely lies within the callback function. Below is the current code I am using. Any suggestions? The HTML form portion represents th ...

Send a quick message with temporary headers using Express Post

When creating a response for a post request in Express that returns a simple text, I encountered an issue. var express = require('express'); var app = express(); var bodyParser = require("body-parser"); var multer = require('multer') ...

Learn the technique of looping through multiple HTML elements and wrapping them in Vue.js easily!

i need to wrap 2 HTML elements together Here is my code snippet using Vue.js <tr> <th v-for="(item9,index) in product_all" :key="item9.id"><center>Qty</center></th> <th v-for="(item99,index) in product_all" :key=" ...