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

448
Visualizações
How to make random images clickable to dedicated pages using javascript?

I have been trying to fix this for days and cannot get it to work, I need the images in my JavaScript code to have their own links to another page on my website (i.e., index1.html, index2.html, index3.html)

The user generates a random image and when the image appears they can click the image and go to the specific page that the image is linked to.

Does that make sense?

function getRandomImage() {
  //declare an array to store the images
  var randomImage = new Array();

  //insert the URL of images in array
  randomImage[1] =  "frames/1.png";  //this needs to have a link
  randomImage[2] =  "frames/2.png";  //this needs to have a link
  randomImage[3] =  "frames/3.png";  //this needs to have a link
  randomImage[4] =  "frames/4.png";  //this needs to have a link
  randomImage[5] =  "frames/5.png";  //this needs to have a link
  randomImage[6] =  "frames/6.png";  //this needs to have a link
  randomImage[7] =  "frames/7.png";  //this needs to have a link
  randomImage[8] =  "frames/8.png";  //this needs to have a link
  randomImage[9] =  "frames/9.png";  //this needs to have a link
  randomImage[10] = "frames/10.png"; //this needs to have a link

  //loop to display five randomly chosen images at once
  for (let i = 0; i < 1; i++) {
    //generate a number and provide to the image to generate randomly
    var number = Math.floor(Math.random() * randomImage.length);

    //print the images generated by a random number
    document.getElementById("result").innerHTML += '<a href="' + randomImage[number] + '"><img src="' + randomImage[number] + '" style="width:450px" /></a>';
  }
}
<button onclick="getRandomImage()">Show Image</button>
<div class="container">
  <span id="result" align="center"></span>
</div>

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

did you try using objects inside your array? I will give an example:


function getRandomImage() {  
    //declare an array to store the images  
    var randomImage = new Array();  
      
    //insert the URL of images in array  
    randomImage[0] =  {img: "frames/1.png", url:"index1.html"};
    randomImage[1] =  {img: "frames/2.png", url:"index2.html"};
    randomImage[2] =  {img: "frames/3.png", url:"index3.html"};
    
    var number = Math.floor(Math.random()*randomImage.length);

    let a = document.createElement("a")
    a.href = randomImage[number].url

    let img = document.createElement("img")
    img.src = randomImage[number].img
    img.style.width = "450px"

    a.append(img)

    document.getElementById("result").append(a)
}

And it's cleaner. I really don't understand the for loop when you already created a random number generator..

about 4 years ago · Juan Pablo Isaza Relatório

0

This can be done simply. Your idea of setting the innerHTML is cool, but your execution of the for loop is a bit off. Here is a working demo using some random images from GIHPY. I'd also recommend using an array of objects in order to easily store the image link and the corresponding URL.

const button = document.getElementById('clickMe')
const images = [
  { img: 'https://media4.giphy.com/media/GvaFelN8tSroAESiS9/giphy.webp', url: 'https://media4.giphy.com/media/GvaFelN8tSroAESiS9/giphy.webp' },
  { img: 'https://media0.giphy.com/media/hIXt83jcZWxUDhC2LD/giphy.webp', url: 'https://media0.giphy.com/media/hIXt83jcZWxUDhC2LD/giphy.webp' },
  { img: 'https://media4.giphy.com/media/6pNyPn7KbMbijMEDf8/giphy.webp', url: 'https://media4.giphy.com/media/6pNyPn7KbMbijMEDf8/giphy.webp' },
  { img: 'https://media1.giphy.com/media/iJaw9MBLbqpgQvhcg4/giphy.webp', url: 'https://media1.giphy.com/media/iJaw9MBLbqpgQvhcg4/giphy.webp' },
];

function getRandomImage() {
    let randomImage;
  for (let i = 0; i < images.length; i++) {
    randomImage = images[Math.floor(Math.random() * images.length)];
  }
  document.getElementById('result').innerHTML = `<a href="${randomImage.img}" target="_blank"><img src="${randomImage.url}" style="width:450px"/></a>`
}

button.addEventListener('click', getRandomImage);
  <button id="clickMe">Show Image</button>
  <div class="container">
       <span id="result"></span>
   </div>

Also, I'd recommend using template literals instead of concatenating stuff together using plus symbols. It gets a bit messy that way))

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