There is two pictures on my website, when i click one of the pictures i want my code to print out either a cat or a frog, using Math.random i want this to be random, i want the user to also get a message that let them know if they are right or wrong.
var outputDiv = document.getElementById("output-div");
var randomNumber;
var message;
function setRandomNumber() {
randomNumber = Math.floor(Math.random() * 100 + 1);
}
function setMessage() {
var image;
if (randomNumber <= 50) {
image = "cat.jpg";
} else {
image = "frog.jpg";
}
message = `
<h3>${image}</h3>
<img src="img/${image}"/>
`;
}
function showMessage() {
outputDiv.innerHTML = message;
}
function initLuckyDay() {
setRandomNumber();
setMessage();
showMessage();
}
initLuckyDay();
<h3>Click the one that you think have a cat!</h3>
<div id="output-div"></div>
<input type="image" src="img/person1.jpg" name="click" class="button" id="clickme" />
<input type="image" src="img/person2.jpg" name="click" class="button" id="clickme" />
You should be able to combine all of these functions into a single function. I would use .setAttribute() to change the source of the image and .innerText to change the message display.
const h3Message = document.getElementById('message'),
htmlImg = document.getElementById('displayImg');
function setImage() {
let random = Math.random(); // generate a random number
if (random < 0.5) {
// set the source of the image
htmlImg.setAttribute('src', 'dog.png');
} else {
htmlImg.setAttribute('src', 'cat.png');
}
// display the message
h3Message.innerText = htmlImg.getAttribute('src');
}
To do it this way, you need to set ids to the HTML elements.
<h3 id="message"></h3>
<img id="displayImg" />