Here's a from-scratch version that does what you're asking for. I'll point out a few things that I did to help you out.
https://codepen.io/anon/pen/VBPpZL?editors=1010
<html>
<body>
<button id="count">0</button>
<p id="test">
Lorem Ipsum is simply dummy text of the printing and typesetting industry.
</p>
</body>
</html>
JS:
window.addEventListener('load', () => {
const button = document.querySelector('#count');
const paragraph = document.querySelector('#test');
const startingFontSize = window.getComputedStyle(document.body, null)
.getPropertyValue('font-size')
.slice(0, 2) * 1;
let clicks = 0;
button.addEventListener('click', () => {
clicks++;
// this is a template literal
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Template_literals
const fontSize = `${startingFontSize + clicks}px`;
button.innerHTML = clicks;
button.style.fontSize = fontSize;
paragraph.style.fontSize = fontSize;
});
});
The code runs when the page is loaded, so we attach an event listener on the window
object listening for the load
event.
We then store references to the button and the paragraph elements. These are const
variables because their values won't change. This also limits their scope to the containing function.
We get the initial font size for the body element, because in this example we aren't explicitly setting a base font in css so we're just using the one for the document. getComputedStyle
is a somewhat expensive operation, and in this case we only need to get it in the beginning because it won't change, so we also store it as a const
. The value is returned as a string like "16px" but we need the number, hence the slice
and multiplying by one to cast the string into a number. parseInt
would also do the same thing.
Notice that clicks
is defined with let
. This means that the variable can be changed. var
still works of course, but in modern practices its best to use const
and let
when declaring variables. This is partly because it forces you to think about what kind of data you're working with.
We add an event listener to the button
element and listen for the click event. First, we increment the clicks
variable. Then we declare fontSize
using a template literal which adds our new clicks
count to the startingFontSize
and "px" to get a string.
Finally, the innerHTML value of the button
element is updated. Then we update the fontStyle property for both elements.