I'm currently on Project 3 in CS50 Web and pretty much completed it. However, there seems to be a bug in unarchiving emails. Whenever I click the unarchive button and it reloads the Inbox, there seems to be 2-4 duplicates. I always have to refresh the page to get them correct again.

Here's the show_mail function, where I create a new div for the email that's clicked on and show it in a new view called id-view with the archive button:

function show_mail(id) {

  // Fetch the email clicked on through their id
  .then(response => response.json())
  .then(email => {

    // Create new view, div and buttons then display the email in it
    document.querySelector("#id-view").innerHTML = '';
    const element = document.createElement('div');
    element.className = "show"
    if (email.archived === false) {
      element.innerHTML = `<div> <p><b>From:</b> ${email.sender}</p> <p><b>To:</b> ${email.recipients} </p> <p><b>Subject:</b> ${email.subject}</p>
<p><b>Timestamp:</b> ${email.timestamp} </p> <hr> <p> ${email.body}</p> <hr> <p><button class="archive">Archive</button></p><p><button class="reply">Reply</button></p></div>`
    else {
      element.innerHTML = `<div> <p><b>From:</b> ${email.sender}</p> <p><b>To:</b> ${email.recipients} </p> <p><b>Subject:</b> ${email.subject}</p>
<p><b>Timestamp:</b> ${email.timestamp} </p> <hr> <p> ${email.body}</p> <hr> <p> <button class="archive">Unarchive</button></p><p><button class="reply">Reply</button></p></div>`


    // Show the mailbox and hide other views
    document.querySelector('#id-view').style.display = 'block'
    document.querySelector('#emails-view').style.display = 'none'

    // Run function archive when archive button is clicked on
    document.addEventListener('click', Event => {
      const element = Event.target;
      if (element.className === "archive") {
        archive(email.id, email.archived)

This is the archive function:

function archive(id, status) {

  // Set archive attribute to the opposite of current status
  fetch(`/emails/${id}`, {
    method: 'PUT',
    body: JSON.stringify({
        archived: !status
  // Load inbox mailbox
  .then( () => {

Thanks for your help!

1 Answer 1


I finally figured it out myself. Instead of using document.addEventListener I used element.addEventListener. This seems to have fixed it. Still don't really know why but if someone could explain, that would be great.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .