Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

127
Views
Random amount of pictures when clicking a button

i have an assignment were i need to create a function that when i click a button it needs to generate a random amount of pictures

var addImgBtn = document.getElementById("add-img-btn");
var outputDiv = document.getElementById("output-div");

function addImg() {
  outputDiv.innerHTML = `
    <img src="img/mann.jpg"/>
  `;
}

function addRandomImg() {
  addImgBtn = Math.floor(Math.random() * 100 + 1);
}

addImgBtn.onclick = addImg;
<input id="add-img-btn" type="button" value="Legg til bilde" />
<div id="output-div"></div>

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

At some point you need to do some iteration to build up the HTML that contains all of the images.

  1. Your onclick should be calling addRandomImg.

  2. You should be assigning the result of the randomiser to a new variable, not addImgBtn.

  3. Use a for...loop to iterate between 0 and rnd, and on each iteration push the image HTML into an array. Once all iterations are complete you can finally update outputDiv with that HTML making sure you join up the elements of the array into a string.

var addImgBtn = document.getElementById("add-img-btn");
var outputDiv = document.getElementById("output-div");

function addRandomImg() {
  const rnd = addImgBtn = Math.floor(Math.random() * 100 + 1);
  let html = [];
  for (let i = 0; i <= rnd; i++) {
    html.push('<img src="https://dummyimage.com/20x20/000/fff"/>');
  }
  outputDiv.innerHTML = html.join('');
}

addImgBtn.onclick = addRandomImg;
img { margin: 2px 2px; }
<input id="add-img-btn" type="button" value="Legg til bilde" />
<div id="output-div"></div>

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!