Search code examples
javascripthtmlfontsswitch-statement

HTML / JS Trying to cycle through font options on website with a switch case but its not functioning


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.


Solution

  • 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.