Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

100
Views
Use math.random to generate pictures

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" />

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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" />
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!