Daniel D.
Daniel D.

Reputation: 184

Execute different function when clicking on button

I'm working on a webpage using Javascript and I want to implement a button so that whenever you click it the text inside the button change to the next text.

Currently I'm doing it like this (also a demo to illustrate what I mean):

CodePen.io

var textCount = 0;
function changeText() {
  var myText = document.getElementById("demo");
  switch (textCount) {
    case 0:{
      myText.innerHTML = "This is the second text";
      textCount++;
    }
    break;
    case 1: {
      myText.innerHTML = "This is the third text";
      textCount++;
    }
    break;
    case 2: {
      myText.innerHTML = "It keeps going on like this";
      textCount++;
    }
    break;
  }
}

Basically I use the switch statement and a counter to go step by step.

Another way I can think of to do this is by having an array that holds all the text and my function just go through it (seems more efficient)


Thanks in advance.

Upvotes: 1

Views: 31

Answers (1)

Hatchet
Hatchet

Reputation: 5428

You are correct, you can make it cleaner & more efficient by using an array, for example:

let list = ['Message one', 'Message two', 'Message three', 'Message four'];

let counter = 0;

function clickHandler () {
    element.textContent = list[counter];
    counter = (counter + 1) % list.length; // If you want to loop messages, otherwise ++
}

Upvotes: 3

Related Questions