-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathchat.js
63 lines (56 loc) · 1.64 KB
/
chat.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
const form = document.querySelector(".typing-area"),
incoming_id = form.querySelector(".incoming_id").value,
inputField = form.querySelector(".input-field"),
sendBtn = form.querySelector("button"),
chatBox = document.querySelector(".chat-box");
form.onsubmit = (e)=>{
e.preventDefault();
}
inputField.focus();
inputField.onkeyup = ()=>{
if(inputField.value != ""){
sendBtn.classList.add("active");
}else{
sendBtn.classList.remove("active");
}
}
sendBtn.onclick = ()=>{
let xhr = new XMLHttpRequest();
xhr.open("POST", "insert-chat.php", true);
xhr.onload = ()=>{
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
inputField.value = "";
scrollToBottom();
}
}
}
let formData = new FormData(form);
xhr.send(formData);
}
chatBox.onmouseenter = ()=>{
chatBox.classList.add("active");
}
chatBox.onmouseleave = ()=>{
chatBox.classList.remove("active");
}
setInterval(() =>{
let xhr = new XMLHttpRequest();
xhr.open("POST", "get-chat.php", true);
xhr.onload = ()=>{
if(xhr.readyState === XMLHttpRequest.DONE){
if(xhr.status === 200){
let data = xhr.response;
chatBox.innerHTML = data;
if(!chatBox.classList.contains("active")){
scrollToBottom();
}
}
}
}
xhr.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhr.send("incoming_id="+incoming_id);
}, 500);
function scrollToBottom(){
chatBox.scrollTop = chatBox.scrollHeight;
}