@malik Iām somewhat of a noob to JS. The āonClickā gets called when you click a button or a div, just to alert the username for now, for testing purposes only. Once I get this bit working, it will pass the username and other user information to a function to display their profile modal.
I am looping through my Moralis user database and displaying a list of usernames. When I click on the users DIV with the id of their username, I want to display their profile modal.
Could you please show me how Iād add the event listener? I tried the below, but still the same issue. It only alerts the last username loaded in the loop regardless of which div/button I click.
loadUsers = async () =>
{
const allusers = await Moralis.Cloud.run("loadUsers");
var userList = parent.document.getElementById('userList');
// var today = new Date();
for (usr of allusers)
{
// lastSeen = today.getDate - usr.updatedAt.getDate;
var dateString = new Date(usr.updatedAt);
let formatted_date = dateString.getDate() + "/" + (dateString.getMonth() + 1) + "/" + dateString.getFullYear()
uList = document.getElementById("userList");
let newUserItem = document.createElement('div');
newUserItem.setAttribute("id", usr.username);
newUserItem.setAttribute("onClick", "alert(usr.username);");
newUserItem.innerHTML = '<b><button id='+usr.username+'>'+usr.username+'</button></b><br><img src='+usr.Avatar._url+' height=50 width=50><br><i>Last Seen</i><br><b>'+formatted_date+'</b>';
newUserItem.addEventListener("click", function(){ alert(usr.username); });
uList.appendChild(newUserItem);
}
console.log(allusers);
return allusers;
}