Change font size dynamically javascript

Asked

Viewed 537 times

0

How to increase and decrease the font with each click? I was looking for ways to do this dynamically, but only found an example in jQuery here, but my project doesn’t use jQuery, how can I do this using pure javascript?

My basic but static code:

function escala(size) {
  var text = document.querySelector('p');
  text.style.fontSize = size + 'px';
}
<button onclick="escala(10)">-</button><button onclick="escala(20)">+</button>
<p>FONT</p>

1 answer

1


You can get the value of the font size through the function window#getComputedStyle and CSSStyleDeclaration#getPropertyValue(), and then just do the treatment as per your need. In a case that is increase/decrease 1px, can be done this way:

let increase = document.getElementById('increase');
let decrease = document.getElementById('decrease');
let main = document.querySelector('main');

let getfontsize = (el) => {
  let size = window.getComputedStyle(el, null)
                   .getPropertyValue('font-size');
  return parseFloat(size);
}

increase.addEventListener('click', () => {
  main.style.fontSize = (getfontsize(main) + 1) + 'px';
})

decrease.addEventListener('click', () => {
  main.style.fontSize = (getfontsize(main) - 1) + 'px';
})
main {
  font-size: 20px
}
<button id='increase'>+</button>
<button id='decrease'>-</button>

<main>
  Mussum Ipsum, cacilds vidis litro abertis. Posuere libero varius. Nullam a nisl ut ante blandit hendrerit. Aenean sit amet nisi. Quem manda na minha terra sou euzis! Sapien in monti palavris qui num significa nadis i pareci latim. Si num tem leite então bota uma pinga aí cumpadi! 
</main>

Browser other questions tagged

You are not signed in. Login or sign up in order to post.