0

I want to make a button that increases the font size by a specific number of pixels or any other unit. I tried this:
---.style.fontSize += "5px"
but it didnt work. What is the correct way?

<html id="html">
<h1>Lorem ispum</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.</p>

<p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a</p>
<button onclick="document.getElementById('html').style.fontSize += '5px'">Bigger Size</button>
</html>

Please no Jquery. Thanks

  • 1
    https://www.w3schools.com/js/js_htmldom_css.asp oh wait why do you have "+="? – MVB76 May 06 '20 at 03:45
  • 2
    Does this answer your question? [Increase the font size with a click of a button using only JavaScript](https://stackoverflow.com/questions/38627822/increase-the-font-size-with-a-click-of-a-button-using-only-javascript) – Luís Ramalho May 06 '20 at 03:45

1 Answers1

1

You need to:

  • Find the current font size which you can get using getComputedStyle,
  • Getting the numeric value of font size,
  • Doing your arithmetic with it and then assigning it back to element's font size

Example:

const button = document.getElementById('resizeButton');
const element = document.getElementById('html');

const sizeExpression = /([\d.]+)(.*)/;
button.addEventListener('click', () => {
  const style = getComputedStyle(element);
  const [size, value, unit] = sizeExpression.exec(style.fontSize);
  element.style.fontSize = `${parseFloat(value) + 5}${unit}`
});
<html id="html">
<h1>Lorem ispum</h1>
<p>Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Aenean commodo ligula eget dolor. Aenean massa.</p>

<p>Cum sociis natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Donec quam felis, ultricies nec, pellentesque eu, pretium quis, sem. Nulla consequat massa quis enim. Donec pede justo, fringilla vel, aliquet nec, vulputate eget, arcu. In enim justo, rhoncus ut, imperdiet a</p>
<button id="resizeButton">Bigger Size</button>
</html>
Soc
  • 7,425
  • 4
  • 13
  • 30