-1

I need your help. I’m a beginner in JavaScript and I want to create a button that increases text by 1px. Can you help me?

3 Answers3

0

This should help! window.getComputedStyle(txt, null).getPropertyValue('font-size'); This is what you can use to get the fontSize of an element.

const txt = document.querySelector("#txt");

function changeFontSize(){
  let fontSize = window.getComputedStyle(txt, null).getPropertyValue('font-size');
  let newFontSize = Number(fontSize.slice(0,2)) + 1
  txt.style.fontSize = `${newFontSize}px`;
 }
#txt {
  font-size: 16px;
 }
<div id="txt">Sample Text</div>
<button onclick="changeFontSize()">Click</button>
Som Shekhar Mukherjee
  • 4,701
  • 1
  • 12
  • 28
0

There are many ways to do that as Som replay above

my way

<body>
    <p class="text" style="color:red">Hello Ahmed</p>
    <button class="btn">Click Me</button>

    <script>
         x = 1;
    document.querySelector(".btn").addEventListener("click",function(){
        increseText();
    })

    function increseText(){
        x++; 
        document.querySelector(".text").style.fontSize = x+'px';
        console.log(x)
    }
    </script>
</body>
Nour
  • 126
  • 8
0

Try this :

<!DOCTYPE html>
<html>

<head>
    <title>Page Title</title>
</head>

<body>

    <h1 id='h'>My First Heading</h1>
    <p id='p'>My first paragraph.</p>
    <button type='button' id='btn'>increases by 1px</button>
    <script>
        document.getElementById("btn").addEventListener("click", function () {
            var el = document.getElementById('h');
            var style = window.getComputedStyle(el, null).getPropertyValue('font-size');
            var fontSize = parseFloat(style);
            el.style.fontSize = (fontSize + 1) + 'px';
        })
    </script>
</body>

</html>

References : How To Get Font Size in HTML

Mohamed Reda
  • 136
  • 1
  • 11