0

I have created with javascript a class called userChat, I would like to be able to add a click event handler to the userChat class so that when I click on userChat it will send me the name of the user I am clicking on, the problem is that I add an addEventListener but it doesn't It works, I don't know what I'm doing wrong, could you please help me, thank you very much.

    function updateUsers(socket){   
    socket.on('updateUsers',function(data){       
        let usuarios = document.querySelector('#usuarios');
        usuarios.innerHTML='';
        for(let i = 0; i < data.users.length; i++){
            let us = `<div class ="userChat">` +data.users[i] +`</div>`;
            usuarios.innerHTML += us;
            

            let userchat = document.querySelector('.userChat');
            userchat.addEventListener('click',function(){
            console.log('estas tocando al usuario: '+data.users[i]);
            });
        }       
    });
    }
  • Can you elaborate on "not working" here--do you get an error? – ggorlen Nov 03 '20 at 15:05
  • You need to use event delegation. This question has been answered beforew. E.g., here: https://stackoverflow.com/questions/34896106/attach-event-to-dynamic-elements-in-javascript – Marc Nov 03 '20 at 15:07
  • If it doesn't work for you, that must be because it includes socket.io and express itself. I need that when I create an html tag from javascript, in this case my userChat class must add a click event handler but mine does not work, I don't know what to do – Jhon Oneall Nov 03 '20 at 15:18

2 Answers2

0

Try this way

let us = `<div class ="userChat" onclick='getUser(data.users[0])'>` +data.users[i] +`</div>`;


function getUser(user){
  // user
}
Nooruddin Lakhani
  • 7,507
  • 2
  • 19
  • 39
0

You are trying to add an event listener to the element which is just created in js (let us = ... in this case). You should add this listener to a parent of this element which is already in DOM and then you can check whether this click is triggered by your element or not. In other words, you need to "delegate" this event to a parent element (event delegation). For example:

 <parent-element>.addEventListener('click', function (e) {
   if (e.target && e.target.classList.contains('userChat')) {
     //do something
   }
 });
hco
  • 655
  • 1
  • 5
  • 15
  • in this case it would be let user or not – Jhon Oneall Nov 03 '20 at 15:49
  • usuarios.addEventListener('click', function (e) { if (e.target && e.target.classList.contains('userChat')) { //do something } }); – Jhon Oneall Nov 03 '20 at 15:50
  • "usuarios" is also created in JS at the beginning of your function so it will not work too. You should find an element that is already in DOM! Maybe, the parent element of "usuarios". – hco Nov 04 '20 at 06:59