Home > Enterprise >  Generate a card with random images
Generate a card with random images

Time:12-04

I have a website where I have cards that have images. I have named the images "wp1", "wp2" and so on. I want the src to have wp(number).png generated on random.

<div >
<div >
          <a href="#"><img src="images/wp18.png" alt="" ></a>
          <h4><a href="#" >download</a></h4>
        </div>
</div>

Above is the card which I have created using div. The main div is "mainWallpapersPanel". I want there to be 18 of these cards in the main div with image src to have the wp no. generated randomly.

CodePudding user response:

To generate random numbers in JavaScript, you can use the Math.random() function. This function returns a floating-point, pseudo-random number in the range 0 to less than 1 (inclusive of 0, but not 1) with approximately uniform distribution over that range.

To generate a random number in a specific range, you can use the following formula:

randomNumber = Math.floor(Math.random() * (max - min   1))   min;

where min is the minimum number in the range and max is the maximum number in the range.

To generate random numbers for the src attribute of the images in your cards, you can use the Math.random() function in a for loop to iterate over the cards and set the src attribute of each image to a random number.

Here is an example:

<div >
  <% for (let i = 0; i < 18; i  ) { %>
    <div >
      <a href="#"><img src="images/wp<%= Math.floor(Math.random() * 18)   1 %>.png" alt="" ></a>
      <h4><a href="#" >download</a></h4>
    </div>
  <% } %>
</div>

In this example, the for loop iterates 18 times and generates a random number in the range 1 to 18 for each iteration. This number is used as the src attribute for the image in the current card.

Note that this example uses a templating language, such as EJS or Handlebars, to insert the generated random numbers into the HTML code. If you are not using a templating language, you can use the = operator to concatenate the generated random numbers with the HTML string instead.

  • Related