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
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.
From the docs:
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 usewindow.getComputedStyle()
instead.