Change font size dynamically javascript

0

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

My basic yet 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>
    
asked by anonymous 25.08.2018 / 05:42

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 according to Your necessity. In a case that is increasing / decreasing 1px , it 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>
    
25.08.2018 / 06:00