JSFiddle - React, Tailwind, and code Playground
HTML
The user has to enter the name of the animal based on the sounds like woof and moo which are inside an array.</br>
What animal says <span id="soundDisplay"></span>:
<input type="text" id="guess" name="guess">
<input type="button" onclick="checkUserInput()" id="butAnimal" name="butAnimal" value="Submit">
JavaScript
/* The following randomly selects an animal and returns animal object,
assigning to the variable "selectedAnimal"
Note the paranthesis around the function and at the end,
or (function(){})();
This is an immediately invoked function expression, or IIFE.
As you continue to learn, you will soon see how powerful this is!
http://stackoverflow.com/questions/6340874/a-javascript-function
*/
var selectedAnimal = (function() {
// Array of animals
var animals = [
{
name: 'dog', says: 'woof'
},
{
name: 'cow', says: 'moo'
},
{
name: 'cat', says: 'meow'
}
];
// Return randomly selected animal
return animals[Math.floor(Math.random() * animals.length)];
})();
// Event handler bound to button in DOM
function checkUserInput() {
var usrInput = document.getElementById('guess').value;
var regex = new RegExp(selectedAnimal.name, 'i');
if (regex.test(usrInput)) {
alert('Congrats! You guessed the right animal!');
} else {
alert('Sorry, that is not correct!');
}
}
// Bind window onload event listener, updates span in HTML with correct animal name
window.onload = function() {
// Display in DOM
document.getElementById("soundDisplay").innerHTML = selectedAnimal.says;
}