I have around 12 different word that I want to be shown in random order when the user clicks a button. A new one every time they press the Button. Is this possible to do with JS? I've tried the method shown here: Random text on button click
Random myRandom = new Random();
TextView textblondin = (TextView) findViewById(R.id.textblondin);
switch(myRandom.nextInt() %3) {
case 0:
textblondin.setText("Text 1");
break;
case 1:
textblondin.setText("Text 2");
break;
case 2:
textblondin.setText("Text 3");
break;
default:
break;
}
}
}
Would appreciate any help that points me in the right direction. I'm new to Javascript.
CodePudding user response:
Try this as your HTML:
<button onclick="randomWord()">
Random Word
</button>
<div id="word">
Click to display a random word
</div>
And this as your JS:
let randomWords = [ 'foo', 'bar' ];
let wordDiv = document.getElementById( 'word' );
function randomWord() {
wordDiv.innerHTML = randomWords[ Math.floor( Math.random() * randomWords.length ) ];
}
When you click the button it will find a random value from your array and set the div with ID "word" to this value. You can change the values in the randomWords
array to whatever you like.