1

I have this function that should I think trigger an alert whenever one of the buttons in my page gets clicked, however nothing happens and if I open the console on the webpage, no errors show. why is it?

document.addEventListener('DOMContentLoaded' , () => {
         document.querySelectorAll('.new-button').forEach (button =>  {
                  button.onclick = () => {
                         const buttonName = button.innerHTML;
                         alert(`you have selected the button!  ${buttonName}`);
                  }

         });

});

I am using the ES6 version of JavaScript if that's any help.

Heretic Monkey
  • 11,687
  • 7
  • 53
  • 122
JustABeginner
  • 321
  • 1
  • 5
  • 14
  • Possible duplicate of [alert() not working in Chrome](https://stackoverflow.com/questions/6184169/alert-not-working-in-chrome) – VirxEC Jun 06 '19 at 12:39
  • 1
    @Virx OP says there are no errors, so I doubt it's a dupe. – VLAZ Jun 06 '19 at 12:40
  • Is the script containing your code possible executed only after `DOMContentLoaded`? – connexo Jun 06 '19 at 12:41
  • I have alerts enabled, and other alerts work fine. – JustABeginner Jun 06 '19 at 12:41
  • 1
    put an console.log just before alert and check if log is printed? – Yogesh Patil Jun 06 '19 at 12:42
  • 2
    I'd add `console.log()` statements to make sure that the "DOMContentLoaded" handler is being called and that there are in fact buttons on the page with that class. – Pointy Jun 06 '19 at 12:43
  • console.log doesn't work. These buttons are added programmatically though, they are not there since the beginning of the loading page. is that why this event doesn't get triggered? – JustABeginner Jun 06 '19 at 12:46
  • 1
    Possible duplicate of [Event binding on dynamically created elements?](https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements) – Heretic Monkey Jun 06 '19 at 13:02

1 Answers1

2

If you dynamically add elements, you have to attach the eventListener to some ancestor element that was statically added. documentworks, but you can add more specific elements for performance. This concept is called delegate listener.

document.addEventListener('click',function(e){
  if(e.target && e.target.matches('.new-button')){
    const buttonName = e.target.innerHTML;
    alert(`you have selected the button!  ${buttonName}`);
    
    const newButton = document.createElement('button');
    newButton.classList.add('new-button');
    newButton.innerHTML = 'click me!!';
    document.getElementById('container').append(newButton);
  }
});
<div id="container">
  <button class="new-button">click me!</button>
</div>
connexo
  • 53,704
  • 14
  • 91
  • 128
  • I think because the buttons I'm talking about are added programmatically by me, they don't respond readily as the stuff that is there from the loading part. How can I link these types of buttons to the event listeners? – JustABeginner Jun 06 '19 at 12:49
  • I modified the answer for the specific problem. – Exceptional NullPointer Jun 06 '19 at 12:53
  • this is how I added the buttons: socket.on('connect', () => { document.querySelector('#add-channel').onclick = function() { var channel = prompt("enter new channel name here"); if (channel != null) { socket.emit('new channel opened', {"channelName": channel}); } } }); socket.on('channel added', data => { const newButton = document.createElement('button'); newButton.className = "new-button btn btn-dark"; newButton.innerHTML = data; document.querySelector('#channels').appendChild(newButton); }); – JustABeginner Jun 06 '19 at 12:55
  • ok the code in this answer works! however I don't understand the difference between my code and yours. Isn't .onclick also an event listener? EDIT: I'll look into delegate listeners, thank you – JustABeginner Jun 06 '19 at 13:00