0

I have a system that will make a new button for a forEach(). Here is the code for that:

 r.forEach(room => {
            socket.on('chat message', (m, i) => {
                let li = $(`<li><button id="${m[i]}">${m[i]}</button></li>`)
                $('#events').append(li)
            })
        });

How would I make a .click() listener for each button?

Oliver Su
  • 84
  • 10
  • 2
    `$('#events').on('click', 'li button', ...)` <= delegate event listener – Taplar Sep 04 '20 at 20:10
  • This..... code also seems problematic. You are looping over something to reference multiple rooms. You then start listen for socket messages, per room, and any time you get a message, which presumably would trigger for each room, you're going to create an li and append it to the page. Which, if there are 40 rooms, it seems like you would create 40 duplicate lis. – Taplar Sep 04 '20 at 20:13
  • That is what I want to do, Taplar – Oliver Su Sep 04 '20 at 20:41

2 Answers2

1

When creating the element, also set up a click event handler:

r.forEach(room => {
  socket.on('chat message', (m, i) => {
    let li = $(`<li><button id="${m[i]}">${m[i]}</button></li>`);
    li.on("click", function(event){ 
       // Your code here
    }
    $('#events').append(li);
  });
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Scott Marcus
  • 57,085
  • 6
  • 34
  • 54
0

Maybe like that:

$('#events').on('click', 'button', function(){
    // Your code here.
})

You should add a class on your buttons to be sure to target them.

  • this creates the event on _all_ buttons under #events – Itamar Sep 04 '20 at 20:14
  • @Itamar it creates one event listener on the parent, that reacts to events from all the children buttons. If there are no buttons within the `#events` that this does not need to happen for, this creates less event listeners and reaches the same results. – Taplar Sep 04 '20 at 20:15
  • yes, but the user requested to create an event for _each_ button, not _all_ buttons – Itamar Sep 04 '20 at 20:16
  • 1
    That's why he should add a class on the buttons he wants to taget with this event. – Najib Doukkani Sep 04 '20 at 20:16
  • Sometimes the users don't know there are better things. @Itamar – Taplar Sep 04 '20 at 20:16
  • This is not better, this solution does not differentiate between buttons – Itamar Sep 04 '20 at 20:17
  • @Najib, No need for class in JQuery, if you have the DOM object in hand :) – Itamar Sep 04 '20 at 20:17