Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

103
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda