0
socket.on('find-match', () => {
  document.getElementById("find-match").innerHTML = '<button class="btn btn-success" id="find-match-btn">Find Match</button>'
});

$("#find-match-btn").on('click', () => {
    console.log('works!');
});

Why do I not get any response when I click the created button? Any help is appreciated!

Tygo
  • 185
  • 3
  • 26
zlotte
  • 201
  • 1
  • 8
  • Is this button created before or after page load? – Adam Jan 30 '19 at 15:17
  • After last user joins button appears to another users who were in the lobby before without page refresh. – zlotte Jan 30 '19 at 15:18
  • Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Adam Jan 30 '19 at 15:19
  • 1
    You'll need to attach the listener to the document / body since the element exists after everything has loaded. – Adam Jan 30 '19 at 15:20
  • 1
    Have you tried to declare the listener inside the socket.on method (under the document.getElementById... line)? – Cristiano Soares Jan 30 '19 at 15:20

2 Answers2

0

This piece of code won't add the listener as you're expecting, since the $("#find-match-btn") will return an empty set because your button is still not available in the DOM.

$("#find-match-btn").on('click', () => {
   console.log('works!');
});

Assuming your socket event is triggered, add the above logic inside the callback.

socket.on('find-match', () => {
  document.getElementById("find-match").innerHTML = '<button class="btn btn-success" id="find-match-btn">Find Match</button>'
  $("#find-match-btn").on('click', () => {
    console.log('works!');
  });
});
Karim
  • 7,479
  • 1
  • 18
  • 31
0

You almost got it right, but since the element you want to add a listener to doesn't exist, the event won't ever trigger. Instead add the listener to the body, and then define which element will trigger it:

setTimeout(() => { // Simulate async
  document.body.innerHTML = '<button class="btn btn-success" id="find-match-btn">Find Match</button>'
}, 1000);

$("body").on('click', '#find-match-btn', () => {
  console.log('works!'); // Check console - it won't print in the snippet
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>

More info: http://api.jquery.com/on/

Delegated event handlers have the advantage that they can process events from descendant elements that are added to the document at a later time. By picking an element that is guaranteed to be present at the time the delegated event handler is attached, you can use delegated events to avoid the need to frequently attach and remove event handlers.

Chris
  • 48,555
  • 16
  • 95
  • 112