Easy way to change FontSize of whole html document

Is there a standard approach to changing the font size of an entire HTML document?

I am thinking of two buttons which increase the font size and the other decrease the font size. Both of these buttons call a JavaScript function;

function increaseFontSize(){
//Increase the font size for the whole document
}

function decreaseFontSize(){
//Decrease the font size for the whole document
}

      

Question

How should I do it? Is there an easier way than the one I have outlined above?

Edit

I am using Bootstrap which comes with its own CSS for each HTML element. Bootstrap defines the default font size (body) as 14px .

+3


source to share


2 answers


One way might be to use units em

in your CSS and you can use Jquery

this solution might work.

You can set a global value in the body and then change that:



$(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>
      

Run codeHide result


+2


source


You need to target the font-size

element style HTML

. You need to make sure the initial value exists so that you can easily change it.

You can do it like this:

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

      

All you need to do is implement value increments:



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

      

I would recommend using a few helper functions to clean up this code:

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

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

      

+1


source







All Articles