In my array called items, there are three items. I randomly selected 2 items, took their labels, and displayed them in 2 boxes within a <p>
tag.
I want the URL of the selected item to be displayed as
a background image of the corresponding box.
For example, if "1" is displayed in the first box, its background image should be the URL of item "1".
How can I achieve this? The image should fit inside the box.
I attempted to use the background-image style method but it's not working.
var array2 = [];
var items = [{
label: '1',
url: 'https://picsum.photos/200/300/?random'
},
{
label: '2',
url: 'https://picsum.photos/200/300/?random'
},
{
label: '3',
url: 'https://picsum.photos/200/300/?random'
}
];
array2 = items.slice();
rvalue();
var item;
function rvalue() {
ptags = document.querySelectorAll('[name="values"]');
boxes = document.getElementsByClassName("box");
for (var index = 0; index < 2; index++) {
var randomIndex = Math.floor(Math.random() * array2.length);
item = array2.splice(randomIndex, 1);
ptags[index].textContent = item[0].label;
//boxes[index]style.backgroundImage = item.url;
ptags[index].dataset.itemIndex = randomIndex;
}
}
.box {
width: calc(15.4% - 4px);
display: inline-block;
border-radius: 5px;
border: 2px solid #333;
border: #000 border-color: #e6e600;
margin: -2px;
background-color: #0F6;
}
.box {
height: 15vh;
display: inline-flex;
align-items: center;
justify-content: center
}
#container {
white-space: nowrap;
text-align: center;
border: px solid #CC0000;
margin: 2px;
margin-right: 2px;
}
.box p {
font-size: calc(2vw + 10px);
}
p {
font: "Courier New", Courier, monospace;
font-size: 30px;
color: #005ce6;
text-align: center;
}
.text {
padding: 20px;
margin: 7 px;
margin-top: 10px;
color: white;
font-weight: bold;
text-align: center;
}
body {
background-size: 100vw 100vh;
}
<div id="container">
<div class="box" id="10">
<p name="values"></p>
</div>
<div class="box" id="11">
<p name="values"></p>
</div>
</div>