This function is supposed to grab a random image from the url everytime its called
function grabImg(){
var img = document.createElement('img');
img.src = 'https://picsum.photos/200/300';
document.getElementById('flex-cat').appendChild(img);
}
And display it in the div below
<div >
<h2>Image Grabber</h2>
<button onclick="grabImg()">Grab Image</button>
<div id="flex-cat"></div>
</div>
Initially when the button is clicked, it calls the function and displays an image fine. However when the button is clicked on multiple times, instead of displaying different random images, the same image which was shown the first time keeps being displayed.
Any tips on how to prevent this?
CodePudding user response:
Using picsum documentation, see Advanced Usage, you can request multiple images of the same size in your browser, add the random query param to prevent the images from being cached. Then you can randomize the number using a helper function, then concatenate using string literal => img.src = https://picsum.photos/200/300?random=${randomRange(10000)}
.
EDIT:
To make it truly random, track the random numbers created with the helper function using an array. If the value is present in the array already, then run the randomImage
method again, else push the value into the array for tracking purposes and return the random value.
const arr = []
function randomImage(max) { // get a random number
let num = ''
let tempNum = ~~(Math.random() * (max))
if(!arr.includes(tempNum)){
num = tempNum
arr.push(num)
}else{
randomImage(max)
}
return arr[arr.length-1]
}
function grabImg() {
var img = document.createElement('img');
img.src = `https://picsum.photos/200/300?random=${randomImage(10000)}`;
document.getElementById('flex-cat').appendChild(img);
}
<div >
<h2>Image Grabber</h2>
<button onclick="grabImg()">Grab Image</button>
<div id="flex-cat">
</div>
</div>