I have a code which shows randomly a URL to a picture. I want to add the random shown URL to the part where the picture is created.
How can I extract the URL from JavaScript and use it in html? Test.jpg should be replaced with the random generated URL.
var myimages = [{
image: "https://cdn.prod.www.manager-magazin.de/images/ca3dd5d1-0001-0004-0000-000000088705_w920_r1.778_fpx42.51_fpy49.99.jpg",
probability: 0.1
}, {
image: "https://p6.focus.de/img/fotos/id_40323993/porsche-cayman-heck.jpg?im=Crop=(0,20,1600,800);Resize=(800,400)&impolicy=perceptual&quality=medium&hash=69314e722c29162f49edafd9b16362ceb1a704219e2a128272824e5d8d585019",
probability: 0.1
}, {
image: "https://i.auto-bild.de/ir_img/1/7/6/3/5/7/9/Alle-Auto-Neuheiten-2019-1200x800-bbcf8a2e46bd3f1f.jpg",
probability: 0.25
}, {
image: "https://cache.pressmailing.net/thumbnail/story_hires/64940fdd-8ec9-4854-98f9-e7f7467414b7/image.jpg",
probability: 0.55
}];
function getImage() {
var rand = Math.random();
var probabilitiy_sum = 0;
for (var i = 0; i < myimages.length; i ) {
probabilitiy_sum = myimages[i].probability;
if (rand <= probabilitiy_sum) {
return myimages[i].image;
}
}
return myimages[myimages.length].image;
}
// Just for testing:
for (var i = 0; i < 1; i ) {
document.getElementById("textbox").innerHTML = getImage() "<br />";
}
<h2>HTML Image</h2>
<img src="test.jpg" width="460" height="345">
<div id="textbox"></div>
CodePudding user response:
Set the src
of an image tag, similar to how you're currently setting the innerHTML of a div:
var myimages = [{
image: "https://cdn.prod.www.manager-magazin.de/images/ca3dd5d1-0001-0004-0000-000000088705_w920_r1.778_fpx42.51_fpy49.99.jpg",
probability: 0.1
}, {
image: "https://p6.focus.de/img/fotos/id_40323993/porsche-cayman-heck.jpg?im=Crop=(0,20,1600,800);Resize=(800,400)&impolicy=perceptual&quality=medium&hash=69314e722c29162f49edafd9b16362ceb1a704219e2a128272824e5d8d585019",
probability: 0.1
}, {
image: "https://i.auto-bild.de/ir_img/1/7/6/3/5/7/9/Alle-Auto-Neuheiten-2019-1200x800-bbcf8a2e46bd3f1f.jpg",
probability: 0.25
}, {
image: "https://cache.pressmailing.net/thumbnail/story_hires/64940fdd-8ec9-4854-98f9-e7f7467414b7/image.jpg",
probability: 0.55
}];
function getImage() {
var rand = Math.random();
var probabilitiy_sum = 0;
for (var i = 0; i < myimages.length; i ) {
probabilitiy_sum = myimages[i].probability;
if (rand <= probabilitiy_sum) {
return myimages[i].image;
}
}
return myimages[myimages.length].image;
}
// Just for testing:
for (var i = 0; i < 1; i ) {
document.getElementById("textbox").innerHTML = getImage() "<br />";
document.getElementById("image").src = getImage()
}
<img id="image" src="test.jpg" width="460" height="345">
<div id="textbox"></div>