Use an image from an array and assign it as the background image for a specific class on an HTML page by

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>

Answer №1

It is recommended to utilize url(link) rather than just link, as shown below:

boxes[index].style.backgroundImage = 'url('+item[0].url+')'; 

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 = 'url(' + item[0].url + ')';

    ptags[index].dataset.itemIndex = randomIndex;
  }

}
.box {
  width: calc(15.4% - 4px);
  border-radius: 5px;
  border: 2px solid #e6e600;
  margin: -2px;
  display: inline-flex;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 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>

Answer №2

To ensure that the image fits within the box, you can apply a few CSS rules to the box class and utilize

boxes[index].style.backgroundImage = "url("+ item[0].url +")"
to specify the background image.

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 = "url("+ item[0].url +")"

    ptags[index].dataset.itemIndex = randomIndex;
  }

}
.box {
  width: calc(15.4% - 4px);
  height: 15vh;
  border-radius: 5px;
  border: 2px solid #333;
  border: #000 border-color: #e6e600;
  display: inline-flex;
  align-items: center;
  margin: -2px;
  background-color: #0F6;
  justify-content: center;
  background-size: cover;
  background-repeat: no-repeat;
  background-position: 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;
}
<div id="container">

  <div class="box" id="10">
    <p name="values"></p>
  </div>
  <div class="box" id="11">
    <p name="values"></p>
  </div>


</div>

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

In Wordpress, I am using Php to display posts. How can I create a new list item after every 3 posts, with each subsequent post displayed inside the new list item?

I am new to using PHP and feeling a bit confused with the code below, which is a team slider. In the <ul> tag, there is one <li> containing 3 nested <div>s (each representing a person). Can someone review my code and help me improve it? I ...

jest - SyntaxError: Unexpected token 'export'

I am currently utilizing vue.js and attempting to incorporate async/await in jest (with vue utils test). it('async/await test', async () => { await wrapper.setData({ foo: 'bar', }); // ... }); Although I can us ...

The table is too large for the parent div in which it is placed, causing

Check out this example I have for putting a table in a div and making it fill the div: ex1_jsfiddle table { font-family: arial, sans-serif; border-collapse: collapse; width: 100%; height: 100%; table-layout: fixed; } td, th { border: 1px sol ...

Having issues with ajax posting functionality

Is the following form correct? <form> <input type="submit" value="X" id="deleteButton" onclick="ConfirmChoice(<?php echo $id; ?>)" /> </form> Here is the function associated with the form: <script type='text/javasc ...

Set the navigation height to fill the entire screen

When the article section expands downwards, the left navigation bar does not extend all the way down. I want the navigation with the background color to expand downwards together with the article text on the right. I attempted to use "height: 100%;" for t ...

What is the best way to conceal the header on a 404 error page?

<HeaderContainer> <Switch> <Route exact path='/counters' component={ParentCounterContainer}/> <Route exact path='/about' component={AboutContainer} /> <Route exact path='/' component={H ...

The content in the html document is not flowing outside a div unless I eliminate the floating property from the div(s)

My goal is to create a page layout with three sections, each floated left based on the device width using media queries in my CSS. I have successfully achieved this, but when I inspect the page using Chrome Developer Tools, I notice that the body is not sp ...

Not every image is contained within a DIV element

My current challenge involves wrapping an img element with a div. The issue I am facing is that the image is loading to the left of the div. I have already set the dimensions of the div to match those of the image, but it still loads incorrectly. I've ...

When performing web scraping with Puppeteer, employing a single selector to target various types of data

As a budding web developer, I have recently delved into coding. My current knowledge is limited to HTML, CSS, JS, and NODE. Currently, I am working on a project involving page scraping and utilizing puppeteer. CHALLENGE - In scenarios like the o ...

Having trouble with a single GET request not functioning properly on Safari due to an Authorization issue in Angular 6

I've encountered this issue in several locations, yet haven't found a clear solution. Only one GET request is showing as unauthorized (401), but when I check the debugger, everything seems to be fine and all other requests are functioning properl ...

Enhanced Fancybox Version 2 adjusts iframe width to fit content

I have been attempting to adjust the width of the iframe in fancybox v2 to fit my content properly. However, every time I try, the content appears too large within the iframe and requires horizontal scrolling to view it all. My goal is to see the entire wi ...

Personalizing Google Map pin

I found some code on Codepen to add pointers to a Google map. Currently, it's using default markers but I want to change them to my own. However, I'm not sure where in the code to make this update. Any examples or guidance would be appreciated. ...

Having difficulty in correctly updating the state using useState along with the previous state

Here is an example of my code: const [formState, setFormState] = useState({ email: null, username: null, password: null, confirmPassword: null, }); const changeHandler = (value, inputType) => { switch (inputType) { case ...

Transferring information from a form with multiple fieldsets to php

I am facing an issue with my form that is built using multiple fieldsets. The problem is related to passing values from each fieldset to welcome.php upon submitting the form. However, when I click submit, nothing happens and the values are not displayed. A ...

What is the best way to share props with all routes in vue.js?

I need to make sure that all components have access to the BASE_URL variable. Here is an example of my App.js: <template> <router-view></router-view> </template> <script> import addJoke from './components/addJoke.vue&ap ...

Encountered a problem when trying to import the function "createToken" into a Node.js middleware

I have developed a model called users in which I included a method named generateToken for generating web tokens. This model is being used with the Sequelize ORM. module.exports = (sequelize, Sequelize) => { const Tutorial = sequelize.define("u ...

Tips for creating a responsive image with a gradient overlay

Having trouble articulating my query, so here's a fiddle: https://jsfiddle.net/8zsqydj0/ .background-img-wrapper:before { content: ""; top: 0; left: 0; position: absolute; height: 100%; width: 100%; background: linear-gradient(to righ ...

Despite successfully connecting to my webservice, the ajax function encounters an error

<script type='text/javascript'> $(document).ready(function () { $("#submit").click(function (e) { e.preventDefault(); var userName = $("#username").val(); var pwd = $("#password").val(); authenticate(use ...

Can anyone provide tips for identifying empty spaces within an HTML document using JavaScript?

Is there a way to detect the spaces between all words on an HTML page using JavaScript? For instance: An example sentence is provided below In this sample, there are visible spaces separating "an" and "example" as well as all subsequent words. Any idea ...

Can you adjust the size of a container based on a breakpoint using a class name in Bootstrap 5?

I am currently working on styling a div using Bootstrap 5. I have a specific requirement where I want the container to have a width of 50 when the screen size is bigger than the medium breakpoint, and by default, it should have a width of 75. In Tailwind, ...