Bilal Khalid
Bilal Khalid

Reputation: 32

How do I make a button that make size bigger in Javascript?

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

Upvotes: 0

Views: 135

Answers (1)

Soc
Soc

Reputation: 7780

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>

Upvotes: 2

Related Questions