Currently, I’m able to change the font size once: decrease (-A), default (A) or Increase (A+). If I click the buttons more than once, it does nothing.
What I want is to be able to increase/decrease the font size but limiting it to clicking twice so the font size doesn’t go beyond -/+ 150%.
Example: When I click on -A
, the font size reduces to 0.75em. I want this to further reduce it to 0.5em if someone clicks it again but that should be the minimum size it can go. Likewise, font size is increased to 1.25em when A+
is clicked but should not increase beyond 1.5em if a user clicks multiple times.
Demo: https://jsfiddle.net/etfcdu10/
HTML:
<button type="button" onclick="changeSizeByBtn(0.75)" name="btn1">-A</button>
<button type="button" onclick="changeSizeByBtn(1)" name="btn2">A</button>
<button type="button" onclick="changeSizeByBtn(1.25)" name="btn3">A+</button>
<hr />
<div id="container">
<h1>This is the title</h1>
<h2>This is a sub title</h2>
<p>I need to increase the texts here by clicking on A+ button and decrease them by clicking -A button above. <br />
The problem here is that it increase/decrease only once. I want it to increase or decrease twice by say 25%. Not Thrice but just twice. How can I go about doing this?</p>
</div>
JS:
var cont = document.getElementById("container");
function changeSizeByBtn(size) {
cont.style.fontSize = size + "em";
}
CSS:
div {
padding: 20px;
border: 5px solid red;
}
h1 {
font-size: 2em;
}
h2 {
font-size: 1.5em;
}
p {
font-size: 1em;
}
3
Answers
Instead of setting the size, make your function change it by the specified amount. Start by changing the values in your HTML:
Then, modify your function to change the size accordingly:
Here’s the final code:
if
sizeChange
is1
, then that means the reset button was pressed to return the text to normal size.fontSizeMultiplier
is updated by addingsizeChange
to it, it can be positive or a negative number depending on if you are increasing or decreasing the size.Keep track of increase and decrease counters separately
numIncreases
for increase counter andnumDecreases
for the decrease counter.with this code, limit the counters
that to prevent the user from decreasing the text too much or the other way around
and finally apply the font size change like you were already doing
Your code only allowed font size changes to occur once per button click.
The ‘changeSizeByBtn’ function represents the change in font size relative to the current size.