I created a simple messaging website but faced a difficult problem: A and B each have two chat groups as shown in the picture, when B switches to B&D group and then A messages in A&B but that message pops up in the B&D group??!!
This is my Javascript code:
const app = initializeApp(firebaseConfig);
const database = getDatabase();
var message = document.getElementById("input"); //input
var btn = document.getElementById("send"); //send button
var order = document.getElementsByClassName("chat-head"); //class name of chat group
var room_name = "a&b"; //A&B is default group when open web (example)
function send(){
push(ref(database, room_name),{
Message: message.value
});
message.value = "";
}
function receive(){
onValue(ref(database, room_name), snapshot => {
snapshot.forEach(element => {
//print name of chat group and messages in it
console.log(room_name, element.val())
});
});
}
function chatHead(){
//set color the chat group which I choose is red
order[0].style.backgroundColor = "red";
for(let i = 0; i < order.length; i++) {
order[i].addEventListener("click", () => {
order[i].style.backgroundColor = "red";
for(let j = 0; j < order.length; j++){
if(j != i){
order[j].style.backgroundColor = "white"; // and others is white
}
}
room_name = order[i].id;
receive();
});
}
}
chatHead();
window.onload = receive();
btn.addEventListener("click", send);