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>
CodePudding user response:
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>
CodePudding user response:
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.