-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.js
99 lines (84 loc) · 2.65 KB
/
main.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
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import replies from "./replies.js"
// get the DOM elements
let externalInput = document.querySelector("#external-input");
const sendButton = document.querySelector(".send-btn");
const chatTemplate = document.createElement("div");
const chatBody = document.querySelector(".chat-body");
let text
// show/hide typing animation
function show() {
document.getElementById("spinner-back").classList.add("show");
document.getElementById("spinner-front").classList.add("show");
}
function hide() {
document.getElementById("spinner-back").classList.remove("show");
document.getElementById("spinner-front").classList.remove("show");
}
function randomReply() {
hide();
// sender = "CodeWomen";
const randomIndex = Math.floor(Math.random() * replies.length);
const randomMessage = replies[randomIndex];
if (randomMessage) {
const index = replies.indexOf(randomMessage);
replies.splice(index, 1);
chatTemplate.innerHTML = `
<div class="left-message">
<div class="sender">
<img class="person-a" src="./images/personA.png" alt="Chatbuddy">
<p class="sender-name">Your friendly Chatbuddy</p>
</div>
<div class="message-text">${randomMessage}</div>
</div>`;
const newMessage = chatTemplate.children[0];
chatBody.append(newMessage);
// make sure bottom messages and input field remain visible
newMessage.scrollIntoView();
} else {
console.log("bye");
}
return randomMessage
}
// function typeWriter(randomMessage) {
// let i = 0
// let speed = 50
// if (i < randomMessage.length) {
// randomMessage += randomMessage.charAt(i);
// i++;
// setTimeout(typeWriter, speed);
// }
// console.log(text);
// }
function sendChat() {
if (externalInput) {
// sender = "WomenDev";
chatTemplate.innerHTML = `
<div class="right-message">
<div class="message-content">
<div class="sender">
<img class="person-b" src="./images/personB.png" alt="Yourself">
<p class="sender-name">You</p>
</div>
<div class="message-text">${externalInput.value}</div>
</div>
</div>`;
const newMessage = chatTemplate.children[0];
chatBody.append(newMessage);
// make sure bottom messages and input field remain visible
newMessage.scrollIntoView();
// clear text in input field
externalInput.value = "";
}
// the random reply comes after 3 seconds, to imitate that someone is writing
show();
setTimeout(randomReply, 3000);
// typeWriter()
}
sendButton.addEventListener("click", function () {
sendChat();
});
externalInput.addEventListener("keypress", function (event) {
if (event.key === "Enter") {
sendChat();
}
});