skip to Main Content

I’m trying to write a program that will change the font size by 1px when clicked. The large button increases by 1px and the low button decreases accordingly.

const text = document.querySelector('.text');
const large = document.querySelector('.large');
const low = document.querySelector('.low');

large.addEventListener('click', () => {
    text.style.fontSize = `calc(${text.style.fontSize} + 1px)`;
});
low.addEventListener('click', () => {
    text.style.fontSize = `calc(${text.style.fontSize} - 1px)`;
});
.text{
    font-size: 36px;
    font-weight: 600;
    font-family: 'Times New Roman', Times, serif;
    color: red;
    user-select: none;
}
<body class="sneg">
    <button class="large">Large</button>
    <button class="low">Low</button>
    <div class="text">Нажми меня</div>
    <script src="./main2.js"></script>
</body>

I tried to make this program using the calc function, but for some reason it didn’t work. I also tried to put ‘100%’ in the calc values ​​and it started working, but a little not as I wanted

2

Answers


  1. I think the problem is that you calc in javaScript the string ’36px’ + the string ‘1px’. You need to get the fontSize your_string then to parseInt it then to subtract or to add your_number and after this you turn it into a string again.

    Login or Signup to reply.
  2. From the docs:

    The read-only style property of the HTMLElement returns the inline style of an element in the form of a live CSSStyleDeclaration object that contains a list of all styles properties for that element with values assigned only for the attributes that are defined in the element’s inline style attribute.

    According to this, if you place the styles of .text in a <style> tag instead of using inline styles, text.style.fontSize will return an empty string (until you modidy it using js). So, you can use window.getComputedStyle() instead.

    const text = document.querySelector('.text');
    const large = document.querySelector('.large');
    const low = document.querySelector('.low');
    
    large.addEventListener('click', () => {
        const fontSize = window.getComputedStyle(text).fontSize;
        text.style.fontSize = `calc(${fontSize} + 1px)`;
    });
    low.addEventListener('click', () => {
        const fontSize = window.getComputedStyle(text).fontSize;
        text.style.fontSize = `calc(${fontSize} - 1px)`;
    });
    .text{
        font-size: 36px;
        font-weight: 600;
        font-family: 'Times New Roman', Times, serif;
        color: red;
        user-select: none;
    }
    <body class="sneg">
        <button class="large">Large</button>
        <button class="low">Low</button>
        <div class="text">Нажми меня</div>
        <script src="./main2.js"></script>
    </body>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search