Get a random String from an Array of Strings
by Dan Vassallo
HTML
<div id="element-container">
<span id="text-container"></span>
<button id="string-changer">Change Dat String!</button>
</div>
CSS
#element-container {
width: 100%;
text-align: center;
}
#text-container {
font-size: 30px;
}
button {
display: block;
margin: 0 auto;
}
JavaScript
// myArray of strings
var myArray = ['word1', 'word2', 'word3']
// change the inner text of the html to a random index's string on
// load
function changeTheString() {
// Get a random index from the array
var randomIndex = myArray[Math.floor(Math.random() * myArray.length)];
$('#text-container').text(randomIndex);
}
changeTheString();
// change the inner text of the html to the random index's string on
// click
$('#string-changer').on('click', function () {
changeTheString();
});