Friday, May 10, 2024
 Popular · Latest · Hot · Upcoming
109
rated 0 times [  110] [ 1]  / answers: 1 / hits: 56479  / 8 Years ago, thu, july 28, 2016, 12:00:00

I'm attempting to increase the font size with the click of a button. I have got the first one to work but I can't get my head around the second one. The second one, every click will increase the font by 1px (I'm pretty much stuck):



<input type=button value=Increase Font Size 100px onclick=increaseFontSizeBy100px()>
<p id=a>Font Size</p>

<input type=button value=Increase Font Size 1px onclick=increaseFontSizeBy1px()>
<p id=b>Font Size by 1 Pixel</p>

<script>
function increaseFontSizeBy100px() {
document.getElementById('a').style.fontSize = 100px;
}

function increaseFontSizeBy1px() {
var font = document.getElementById('b').style.fontSize;
font++;
}
</script>

More From » button

 Answers
10

Change your function to as in the code below and see what happens:



function increaseFontSizeBy100px() {
txt = document.getElementById('a');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
txt.style.fontSize = (currentSize + 100) + 'px';
}
function increaseFontSizeBy1px() {
txt = document.getElementById('b');
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
txt.style.fontSize = (currentSize + 1) + 'px';
}


Note: as you can see, there are a lot of duplication in both functions. Therefore, if I were you, I would change this function to increase the fontsize by a given value(in this case, an int).



So, what we can do about it? I think we should turn these functions into a more generic one.



Take a look at the code below:



function increaseFontSize(id, increaseFactor){
txt = document.getElementById(id);
style = window.getComputedStyle(txt, null).getPropertyValue('font-size');
currentSize = parseFloat(style);
txt.style.fontSize = (currentSize + increaseFactor) + 'px';
}


Now, for example, in your button Increase Font Size 1px, you should put something like:



<input type=button value=Increase Font Size 1px onclick=increaseFontSize(b, 1)>
<p id=b>Font Size by 1 Pixel</p>


But, if we want a Decrease Font Size 1px, what we can do? We call the function with -1 rather than with 1.



<input type=button value=Decrease Font Size 1px onclick=increaseFontSize(b, -1)>
<p id=b>Font Size by -1 Pixel</p>


We solve the Decrease Font Size problem as well. However, I would change the function name to a more generic one and call it in both two functions that I would create: increaseFontSize(id, increaseFactor) and decreaseFontSize(id, decreaseFactor).



That's it.


[#61228] Tuesday, July 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
casandra

Total Points: 334
Total Questions: 93
Total Answers: 104

Location: Denmark
Member since Tue, Jul 19, 2022
2 Years ago
;