Skip to content
Advertisement

How do I properly make click event on fetched “buttons”?

I fetch all users from database via this code

fetch("/api/v1/users", {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
      }
})
.then(function(res) {
    return res.json();
})
.then(function(json) {
    json.data.forEach((elem) => {
        Object.values(elem).forEach((item) => {
            if(item != "" && typeof item == "string") {
                document.querySelector('.users__list').appendChild(users.createElement('div', 'users__user-field', '', `<p>${item}</p>`))
            }
        })
    })
})

After they fetched, I generate an element and add that element to the list. That works fine, but!

I have this part of code

const selectableUsers = {
    users: document.querySelectorAll('.users__user-field'),
    click(elem) {
        this.reset()
        elem.classList.toggle('selected')
    },
    reset() {
        this.users.forEach((elem) => {
            elem.classList.remove('selected')
        })
    }
}

window.onload = () => {
    document.querySelectorAll('.users__user-field').forEach((elem) => {elem.addEventListener('click', () => {selectableUsers.click(elem)})})
}

In my logic, after elements generated, and window loaded, all items with class users__user-field must have a click event to toggle selected class. But that’s doesn’t work. I have no idea why. Can you help me?

Advertisement

Answer

The problem is that you suppose that users are fetched and added as DOM elements loading the window, which is wrong. Once window loaded, you try to add select event to an empty list of DOM elements, you should set the select behavior after fetching users list like that :

fetch("/api/v1/users", {
    method: 'GET',
    headers: {
        'Content-Type': 'application/json'
      }
})
.then(function(res) {
    return res.json();
})
.then(function(json) {
    json.data.forEach((elem) => {
        Object.values(elem).forEach((item) => {
            if(item != "" && typeof item == "string") {
                document.querySelector('.users__list').appendChild(users.createElement('div', 'users__user-field', '', `<p>${item}</p>`))
// -------------->
                document.querySelectorAll('.users__user-field').forEach((elem) => {elem.addEventListener('click', () => {selectableUsers.click(elem)})})            
// -------------->
             }
        })
    })
})
Advertisement