skip to Main Content

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.

2

Answers


  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.

    Login or Signup to reply.
  2. 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;
    

    }

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search