How can I dynamically increase font size with Javascript and why is my current function not working?

22,902

Solution 1

This script should work:

function changeFontSize(fontvar) {
    var div = document.getElementById("webchat_history");
    var currentFont = div.style.fontSize.replace("px", "");

    div.style.fontSize = parseInt(currentFont) + parseInt(fontvar) + "px";
}

Solution 2

I found this amazing script: https://github.com/simplefocus/FlowType.JS

Demo: http://simplefocus.com/flowtype/demo.html

Share:
22,902
Kenny Johnson
Author by

Kenny Johnson

Updated on March 21, 2020

Comments

  • Kenny Johnson
    Kenny Johnson about 4 years

    I'm trying to increase the font size of my page using a javascript function but it's not working. Is there a syntax problem with my code or is it not possible to do what I'm trying to do?

    Javascript:

    function changeFontSize(fontvar) {
    var div = document.getElementById("webchat_history");
    var currentFont = div.style.fontSize.value;
    
    div.style.fontSize = currentFont + fontvar+ "px";
    }
    

    HTML:
    <span onClick="changeFontSize(10);" style="font-size:16px;">Aa</span>

    I want to increase it by x amount (fontvar) rather than specifying a specific font size because my font sizes are set in an external stylesheet. When/if I need to modify the stylesheets, I'd rather not have to update the Javascript too.

  • Kenny Johnson
    Kenny Johnson about 11 years
    No change. I'm getting "Object Required" in the Javascript Console on IE8 still
  • LRA
    LRA about 11 years
    check my answer again, I have made some changes
  • Kenny Johnson
    Kenny Johnson about 11 years
    I appreciate all your help, but I think I found my problem. "webchat_history" is a class, not an Id. So this problem actually had nothing to do with the function.
  • LRA
    LRA about 11 years
    yes, but the solution depends on how many divs you have with same class, do you have one or many?
  • LRA
    LRA about 11 years
    if it's only one you can use: var div = document.getElementsByClassName("webchat_history")[0];