Start from here,
for (let i = 1; i < 5; i++){
oneUser(i);
}
While calling the api inside for loop, pass index as well,
Then do api call as like yours,
function oneUser(i) {
fetch('https://randomuser.me/api/')
.then((response) => {
return response.json();
})
.then((response) => {
getPic(response, i);
})
.catch(error => {
console.error(error);
})
}
with one change that passing the received index to the getPic(i)
function..
Then in getpic()
, have the same code as like you did for picText
, info
, and moreData
and append these to picDiv
innerHTML..
const picText = `<div> <img src="${response.results[0].picture.large}"/> `;
const info = `${response.results[0].name.first}, ${response.results[0].name.last} `;
document.getElementById('picDiv').innerHTML += picText + info;
const moreData = `<div id="moreData" style="display:none"> ${response.results[0].dob.date}, ${response.results[0].location.street.name}, ${response.results[0].location.street.number}</div>`;
document.getElementById('picDiv').innerHTML += moreData;
Then create a button with unique id
from received index i
..
<button id=moreData${i}>More details</button>
Initially we are making the moreData section alone in display none like,
<div id="moreData" style="display:none">
and the complete function like,
function getPic(response, i){
const picText = `<div> <img src="${response.results[0].picture.large}"/> `;
const info = `${response.results[0].name.first}, ${response.results[0].name.last} `;
document.getElementById('picDiv').innerHTML += picText + info;
const moreData = `<div id="moreData" style="display:none"> ${response.results[0].dob.date}, ${response.results[0].location.street.name}, ${response.results[0].location.street.number}</div>`;
document.getElementById('picDiv').innerHTML += moreData;
const button = `<button id=moreData${i}>More details</button> <br /><br />`;
document.getElementById('picDiv').innerHTML += button;
getMoreData();
}
At the end call getMoreData()
, with same for loop you did first like,
function getMoreData(){
for (let i = 1; i < 5; i++) {
const elem = document.getElementById('moreData' + i);
if(elem){
elem.addEventListener('click', () => {
document.getElementById('moreData' + i).previousSibling.style.display = "block"
});
}
}
}
In this above function we are making the moredata
to be displayed once clicking on the more details button by adding unique eventlistener to each button..