Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

104
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda