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

191
Views
Adding Hyperlinks to Images in a JavaScript Random Images Array

I have a random image generating array and I am hoping to insert hyperlinks associated with each image but I can't seem to find an answer or solution that works; or that I can understand enough to adapt to my situation/code. I am a javascript novice just trying to learn as much as I can as I go! Thanks in advance to any help, all is appreciated!

JS as follows:

var random_images_array = ['img1.jpg', 'img2.jpg', 'img3.jpg'];

    
function getRandomImage(imgAr, path) {
    path = path || 'img/'; // default path here
    var num = Math.floor( Math.random() * imgAr.length );
    var img = imgAr[ num ];
    var imgStr = '<img src="' + path + img + '" alt = "">';
    document.write(imgStr); document.close();
}

HTML:

<div id="heroImage" style="text-align: center">
        <script type="text/javascript">getRandomImage(random_images_array, 'img/heroImage/')</script>
</div>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

picsum answers GETs from picsum.photos/width/height by redirecting to a random image with the requested dimensions.

In order to have the image and the link match, you must make the picsum GET request and get the redirect URL from the response "Location" header. That's the URL that should be placed in the DOM.

After running the snippet, right-click the image and open it in new tab. Note the same image appears. Using the original GET url as the href will direct user to a new random image.

// super simple promise-returning http request
async function get(url) {
  return new Promise(resolve => {
    const xmlHttp = new XMLHttpRequest();
    xmlHttp.addEventListener("load", () => resolve(xmlHttp));
    xmlHttp.open("GET", url);
    xmlHttp.send();
  });
}

async function getRandomImage(width, height) {
  const url = `https://picsum.photos/${width}/${height}`;
  let res = await get(url);

  // this is the important part: we need the redirect url for the image
  const redirectURL = res.responseURL
  const html = `<a href='${redirectURL}' target='_blank'><img src="${redirectURL}" alt=""/></a>`;
  const el = document.querySelector('#heroImage')
  el.innerHTML = html;
}

getRandomImage(200, 300)
<div id="heroImage" style="text-align: center">
</div>

Notice that we don't need to fool around with a random pick from an array of URLs. picsum does the randomizing on the initial GET.

about 4 years ago · Juan Pablo Isaza Report

0

Here's what I think you're trying to accomplish. Note: don't use document.write -- that has very specific uses and this isn't a good one. Rather use the innerHTML property (and there are other ways too). I modified the code so you could see the result in the snippet.

let random_images_array = [{
    img: "https://picsum.photos/200/300?1",
    link: "https://google.com"
  },
  {
    img: "https://picsum.photos/200/300?2",
    link: "https://yahoo.com"
  },
  {
    img: "https://picsum.photos/200/300?3",
    link: "https://loren.picsum.com"
  }
];

function getRandomImage(imgAr, path) {
  path = path || 'img/'; // default path here
  path = ''; // JUST FOR S.O. TESTING
  let num = Math.floor(Math.random() * imgAr.length);
  let img = path + imgAr[num].img;
  let imgStr = `<a href='${imgAr[num].link}'><img src="${img}" alt="" border="0" /></a>`;
  document.querySelector('#heroImage').innerHTML = imgStr;
}

window.addEventListener('DOMContentLoaded', () => {
  getRandomImage(random_images_array, 'img/heroImage/')
})
<div id="heroImage" style="text-align: center">
</div>

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!