Here is my javascript code that is able to show the list of users using the fetch api.
I want to click a user and show his info in a model using the javascript and fetch api.
I am not able to add the markup for the model.
I tried creating the modal in the for each loop but that works only for 1st user on the list.
const url = "https://randomuser.me/api/?results=12 ";
var userView = document.querySelector(".gallery");
fetch(url)
// Convert the data into JavaScript
.then((response) => response.json())
// Now we can use the data
.then((data) => {
// Log out the data
//console.log(data);
insertUsers(data);
})
// Log out any errors
.catch((error) => console.error(error));
function insertUsers(users) {
users.results.forEach((user) => {
userView.insertAdjacentHTML(
"beforeend",
`<div class="card">
<div class="card-img-container">
<img class="card-img" src="${user.picture.large}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${user.name.first}</h3>
<p class="card-text">${user.email}</p>
<p class="card-text cap">${user.location.city}, ${user.location.city}</p>
</div>
</div>`
);
document.querySelector('.card-img').addEventListener('click', function(){
console.log(user.name.first);
})
});
}
I am trying to open a model on the click of the image of user.
here is the markup for the model i want to show.
<div class="modal-container">
<div class="modal">`enter code here
<button type="button" id="modal-close-btn" class="modal-close-btn"><strong>X</strong></button>
<div class="modal-info-container">
<img class="modal-img" src="https://placehold.it/125x125" alt="profile picture">
<h3 id="name" class="modal-name cap">name</h3>
<p class="modal-text">email</p>
<p class="modal-text cap">city</p>
<hr>
<p class="modal-text">(555) 555-5555</p>
<p class="modal-text">123 Portland Ave., Portland, OR 97204</p>
<p class="modal-text">Birthday: 10/21/2015</p>
</div>
</div>
you could bind multiple click
on the same element.I suggest you create dom and bind event one by one.
function insertUsers(users) {
users.results.forEach((user) => {
const dom = document.createElement('div')
dom.setAttribute('class','card')
dom.innerHTML = `
<div class="card-img-container">
<img class="card-img" src="${user.picture.large}" alt="profile picture">
</div>
<div class="card-info-container">
<h3 id="name" class="card-name cap">${user.name.first}</h3>
<p class="card-text">${user.email}</p>
<p class="card-text cap">${user.location.city}, ${user.location.city}</p>
</div>
`
//bind click event only to current element.
dom.querySelector('.card-img').addEventListener('click',function(){
console.log(user.name.first);
})
userView.appendChild(dom)
});
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.