I have 6 different options for fonts and I created a button in HTML to call a function onclick. I click it once adn the change works, but when I click it again it does nothing. Definitely missing something and I can”t figure out what it is.
function changeFont() {
var font = "Arial";
var fontNum = 1;
fontNum++;
switch (fontNum) {
case 1:
font = "Josefin Sans";
break;
case 2:
font = "Montserrat";
break;
case 3:
font = "Lora";
break;
case 4:
font = "Suse";
break;
case 5:
font = "Fenix";
break;
case 6:
font = "Courier Prime";
}
document.body.style.fontFamily = font;
if (fontNum >= 6) {
fontNum = 0;
}
}
<input type="button" id="font-toggle" value="Aa" onclick="changeFont()" />
It changes to Montserrat, but nothing after.
Any guidance would be appreciated, thank you.
1
You declared var fontNum = 1
in the click event which means its value is not saved for next click, so when you click the button fontNum
changes from 1 to 2 => font
become “Montserrat” everytime.
Move the fontNum
out of the function and it’ll work.
1
While you already have an answer I still want to give you another answer that solves the issue with a completely different approach.
Your code could be simplified a lot and change/remove the issue with it.
Your code is not very abstract and could be simplified a lot. Simply sue an array for your fonts and then toggle through the array.
To get to the start of the array you can use fontNum = (fontNum + 1) % Fonts.length;
. This will also remain to work when adding more fonts to the array. There will be no further need to change the function code.
const Fonts = ['Arial', 'Josefin Sans', 'Montserrat', 'Lora', 'Suse', 'Fenix', 'Courier Prime'];
let fontNum = 0;
function changeFont() {
fontNum = (fontNum + 1) % Fonts.length;
document.body.style.fontFamily = Fonts[fontNum];
// shows current selected Font
console.clear()
console.log(Fonts[fontNum]);
}
<input type="button" id="font-toggle" value="Aa" onclick="changeFont()" />
1
Do some changes according to it.
var fontNum = 0;
function changeFont() {
var font;
fontNum++;
switch (fontNum) {
case 1:
font = "Josefin Sans";
break;
case 2:
font = "Montserrat";
break;
case 3:
font = "Lora";
break;
case 4:
font = "Suse";
break;
case 5:
font = "Fenix";
break;
case 6:
font = "Courier Prime";
break;
default:
font = "Arial";
fontNum = 0; // Reset fontNum after the last case
}
document.body.style.fontFamily = font;
console.clear();
console.log(font);
}
<input type="button" id="font-toggle" value="Aa" onclick="changeFont()" />
2