[JavaScript] Font Size Larger/Smaller


Make font size of your website larger/smaller via JavaScript.

First we implement button-like element by HTML and SCSS:

HTML

<div class="font-adjust">
  <span id="font-larger">A+</span>
  <span id="font-smaller">A-</span>
</div>

SCSS

.font-adjust {
  float: right;
  margin-right: 3px;

  span {
    &:hover {cursor: pointer;}
    padding: 5px 5px;
    background: #fff;
    border-radius: 4px;
  }
}

When users click on A+/A-, make larger/smaller font size of div element whose class is .main-content:

JavaScript

var fl = document.getElementById("font-larger");
fl.onclick = function() {
  var contents = document.querySelectorAll(".main-content");
  for (var i = 0; i < contents.length; i++) {
    var content = contents[i];
    if (content.style.fontSize == "") {
      content.style.fontSize = "1.0em";
    }
    content.style.fontSize = (parseFloat(content.style.fontSize) + 0.25) + "em";
  }
}

var fs = document.getElementById("font-smaller");
fs.onclick = function() {
  var contents = document.querySelectorAll(".main-content");
  for (var i = 0; i < contents.length; i++) {
    var content = contents[i];
    if (content.style.fontSize == "") {
      content.style.fontSize = "1.0em";
    }
    content.style.fontSize = (parseFloat(content.style.fontSize) - 0.25) + "em";
  }
}

References:

[1]font size larger/smaller · twnanda/twnanda@7233501 · GitHub
[2]javascript font size increase/decrease
[3]Change Text Size On Click With JavaScript