0

I want to change the font size of an element periodically but it isn't working.

I tried console.log() to get the size of the font but it returned some info in curly brackets. (I'm fairly new to JavaScript so I don't know if that is something which is expected). I tried looking up the documentation but even then it doesn't work.

JavaScript:

var text = document.getElementById("main");
var x = setInterval(incFont, 100);
console.log(document.getElementById("main").style.fontSize);
var size = parseInt(document.getElementById("main").style.fontSize, 10);

function incFont()
{
    size = size + 1;
    document.getElementById("main").style.fontSize = "" + size;
}

HTML:

<p id="main">
    Text-Growing
</p>
<script src="function.js"></script>

Output of console.log:

{"notifyType":"consoleItemLog","message":{"message":"","styles":"","hasFormatString":true,"fileUrl":"file:///D:/170911092/Lab%203/function.js","lineNumber":3,"columnNumber":1}}

jkdev
  • 11,360
  • 15
  • 54
  • 77
6575
  • 67
  • 3
  • What does the markup look like for your `#main` element? Where is your `console.log()`? What exactly does the console message look like (you can [edit your question](https://stackoverflow.com/posts/57470747/edit) to add screenshots)? – Phil Aug 13 '19 at 03:31
  • 1
    You're also missing the unit suffix for your [font-size](https://developer.mozilla.org/en-US/docs/Web/CSS/font-size#Possible_approaches), ie `px`, `em`, etc – Phil Aug 13 '19 at 03:35
  • Added the HTML code and console.log output. Will I need suffix if I am incrementing the size I got from the script? – 6575 Aug 13 '19 at 03:37
  • console.log(size) before line 4 but I defined size before that. – 6575 Aug 13 '19 at 03:39
  • 1
    There's no call to `console.log()` in the code you've showed us, so we are not sure what you are logging. – laptou Aug 13 '19 at 03:40

1 Answers1

0

Without some units, see ways to specify the font size, you cannot update style.fontSize.

The object returned from document.getElementById("content").style is CSSStyleDeclaration, to set properties you can also use setProperty().

The .fontSize style name is actually font-size so either of the following will update the CSS;

document.getElementById("main").style.fontSize = '12px';
document.getElementById("main").style.setProperty('font-size','12px');
Dave Anderson
  • 11,836
  • 3
  • 58
  • 79
  • It increments only once even though it loops many times. Even after adding units. – 6575 Aug 13 '19 at 03:45
  • This does not retrieve the initial font-size of the element for which you need `getComputedStyle()` but there's already a duplicate link with all that information – Phil Aug 13 '19 at 03:49