For this exercise I am trying to create a mailbox mostly based on javascript. After all the emails are fetched, I display them with a for-of-loop. What I need to do now is provide an event listener to each email that runs the "show_email" function when I click on the mail.
Unfortunately when I run this code and then try to click on an email, it always loads the email with the email.id that is 1, instead of the email with the email.id according to the loop position.
Right now I have no idea how to fix this. Thanks for any help!
function inbox() {
console.log('running function inbox');
fetch('/emails/inbox')
.then(response => response.json())
.then(emails => {
// looping through all mails to display them on the screen
for (email of emails){
const element = document.createElement('div');
element.innerHTML = `<div id="emails-item">
<span id="emails-address">${email.sender}</span>
<span id="emails-subject">${email.subject}</span>
<span id="emails-timestamp">${email.timestamp}</span>
</div>`;
// Link to open individual email (here it does not do what I want)
element.addEventListener('click', () => show_email(email.id));
document.querySelector('#emails-view').append(element);
}
});
}
function show_email(id) {
console.log(`Email ${id} is loaded...`)
}