I have an interesting bug, I don't know if it comes from a point that I ignore from javascript but it doesn't make sense at all!
It is a small messaging application where you can play chifoumi.
Here in the photo we have received 2 game requests, characterized with the "answer (Répondre au jeu)" button, the button is deactivated when we have answered! So far yes, BUT the problem is that the first button you see here is no longer listened to, in fact, it is as if the listener associated with the button had flown by itself.
So I don't understand why the button loses its listener; knowing that before clicking on the other it works perfectly (pressing a button just fills the text box at the bottom, if I don't send it the button remains active).
Here is my code :
socket.on("chifoumi", function(result) {
var win = document.getElementById("content");
var date = new Date(result.date);
var hours = date.getHours();
var minutes = date.getMinutes();
var seconds = date.getSeconds();
if (date.getHours() < 10)
hours = "0" + date.getHours();
if (date.getMinutes() < 10)
minutes = "0" + date.getMinutes();
if (date.getSeconds() < 10)
seconds = "0" + date.getSeconds();
let main = document.getElementsByTagName("MAIN");
if (result.from == currentPseudo) {
main[0].innerHTML += "<p class=\"chifoumi\">" + hours + ":" + minutes + ":" +
seconds + " - [chifoumi] : Défi envoyé à " + result.to + "</p>";
} else if (result.from != currentPseudo) {
main[0].innerHTML += "<p class=\"chifoumi\">" + hours + ":" + minutes + ":" +
seconds + " - [chifoumi] : " + result.from + " te défi à Paper-Rock-Scissors-Lizard-Spock. <button class=" + result.from + " name = \"btn\"> Répondre au jeu </button></p > ";
win.className = "buzz";
buttonListener();
}
});
Each time I add a new button, I update all the listeners of my buttons, because same problem when I added a new button, the others lost their listener !
function buttonListener() {
let btn = document.getElementsByName("btn");
console.log(btn);
for (let bt of btn) {
////LISTENER MULTI BOUTON
console.log(bt);
bt.addEventListener("click", function(e) {
startGame = 1;
msgChiff = "/chifoumi @" + this.className + " :";
document.getElementById("monMessage").value = "/chifoumi @" + this.className + " :";
});
}
}
I don't think the rest of my code will do you any good. I do not touch the listener elsewhere.
I thank you in advance..
Answer on the behalf of user253751
It's probably because you are setting innerHTML. By setting innerHTML, you are telling the browser to delete everything that's inside main[0], and then add the things in the innerHTML string back. But the innerHTML string doesn't have any event listeners. So, you don't get one. Try using appendElement instead, which adds a new element, without changing any of the others.