Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Function to change font size in js. how to add zooming limit?

Tags:

javascript

I have function:

    function changeFontSize(points) {
        var e = document.getElementsByTagName("BODY")[0];
        var style = window.getComputedStyle(e);
        var size = style.getPropertyValue('font-size');
        size = size.replace("px", "");
        size = size * 1;
        size = size + points;
        //if(size <= 0 && size  <= 3){
            e.style.fontSize = size + "px";
            localStorage.setItem("size", size);
        //}
    }

    function saveFontSize() {
        var size = localStorage.getItem("size");
        if (size !== null) {
            var e = document.getElementsByTagName("BODY")[0];
            e.style.fontSize = size + "px", '!important';
        }
    }

    document.addEventListener("DOMContentLoaded", saveFontSize);



<a href="#" onclick="changeFontSize(1);">plus</a>
<a href="#" onclick="changeFontSize(-1);">minus</a>

The above code works correctly. The above function enlarges and reduces the font size on my website.

I need to limit the function of this function to a maximum of 3 times the size of the font. The font size reduction (lower font size) can not be smaller than its original (original size).

How to do it? Please help.

like image 902
trafiek Avatar asked Oct 16 '22 06:10

trafiek


1 Answers

You could store the initial font size and then make use of Math.min and Math.max:

body.style.fontSize = Math.max(
  initialBodyFontSize, 
  Math.min(
    initialBodyFontSize * 3, 
    getBodyFontSize() + points
  )
) + 'px';

Demo (without the loading/saving through localStorage part, since it's not possible here):

{
  var body = document.querySelector('body');
  var initialBodyFontSize;
  
  // Note: this supposes the body's font size is expressed in px
  function getBodyFontSize() { 
    return parseFloat(window.getComputedStyle(body).getPropertyValue('font-size'));
  }

  function changeBodyFontSize(points) {
    body.style.fontSize = Math.max(
      initialBodyFontSize, 
      Math.min(
        initialBodyFontSize * 3, 
        getBodyFontSize() + points
      )
    ) + 'px';
    console.log(body.style.fontSize);
  }

  document.addEventListener('DOMContentLoaded', function () {
    initialBodyFontSize = getBodyFontSize();
  });
}
<a href="#" onclick="changeBodyFontSize(1);">plus</a>
<a href="#" onclick="changeBodyFontSize(-1);">minus</a>

Also note that you should generally avoid onclick and similar attributes, and prefer addEventListener JS calls on the associated DOM elements instead.

like image 73
Jeto Avatar answered Oct 21 '22 03:10

Jeto