28
loading...
This website collects cookies to deliver better user experience
// index.html
<!DOCTYPE html>
<html lang="en">
<head>
<title>Chatbot</title>
<link rel="stylesheet" href="style.css" />
<script type="text/javascript" src="index.js" ></script>
</head>
<body>
<h1>Chatbot</h1>
<div id="container" class="container">
<input id="input" type="text" placeholder="Say something..." autocomplete="off" />
</div>
</body>
</html>
style.css
file to add styling to our application:* {
box-sizing: border-box;
}
html {
height: 100%;
}
body {
font-family: 'Poppins', sans-serif;
background-color: #fff;
height: 100%;
margin: 0;
}
.container {
width: 100%;
height: 100%;
}
enter
key.addEventListener
method is needed. It calls up a function whenever a specified event is delivered to the target. The two events our addEventListener
listens for are:DOMContentLoaded
- this event fires when the initial HTML document has been completely loaded and parsed, without waiting for stylesheets, images, and subframes to finish loading.keydown
- this event is fired for all keys, regardless of whether they produce a character value.keydown
event is a KeyboardEvent.code
property which provides a code indicating which of the user’s keyboard keys is pressed. For example, a lowercase "a" will be reported as 65 by keydown
and keyup
. An uppercase "A" is reported as 65 by both events.keydown
event, we can create an effective way of sending a message to the chatbot by pressing the enter
key. Our addEventListener
would listen and respond anytime the enter
key is pressed.document.addEventListener("DOMContentLoaded", () => {
inputValue.addEventListener("keydown", (e) => {
if (e.code === "Enter") {
let input = inputValue.value;
inputValue.value = "";
output(input);
}
});
});
e.code === "Enter"
indicates the Keycode 13 directly assigned to the Enter
button. To know more about Keycodes, read up on the KeyboardEvent
object..value = ""
makes this possible. We can use .reset()
if our input field was a form
tag but sadly, it isn’t.function output(input) {
//remove all characters except word characters, space, and digits
let text = input.toLowerCase().replace(/[^\w\s]/gi, "").replace(/[\d]/gi, "").trim();
text = text
.replace(/ a /g, " ") // replaces 'tell me a story' to 'tell me story'
.replace(/i feel /g, "")
.replace(/whats/g, "what is") // replaces "whats" to "what is"
.replace(/please /g, "")
.replace(/ please/g, "")
.replace(/r u/g, "are you"); //replaces "r u" to "are you"
}
whats up
to what is up
or r u
to are you
. If the user says what is going on
, whats going on
, or what's going on
, they will all lead to the same valid bot response.const userTexts = [
//0
["hi", "hey", "hello", "good morning", "good afternoon", "good day"],
//1
["how are you", "how is life", "how are things", "how are you doing",
"are you doing good", "are you fine", "how is your day going", "how is your day",
"what's up", "whats up", "you good"],
//2
["what are you doing", "what is going on", "what is up", "how is your day",
"what's up", "whats up", "you good"],
//3
["how old are you", "are you old"],
//4
["who are you", "are you human", "are you bot", "are you human or bot"],
//5
["who created you", "who made you", "were you created"]
]
const botReplies = [
//0
["Hello!", "Hi!", "Hey!", "Hi there!","Howdy"],
//1
[
"Fine... and you?",
"Pretty well, and you?",
"Fantastic, and you?"
],
//2
[
"Nothing much",
"About to go to sleep",
"Can you guess?",
"I don't know actually"
],
//3
["I am infinite"],
//4
["I am just a bot", "I am a bot. What are you?"],
//5
["The one true God, JavaScript"]
]
const alternative = [
"Same",
"Go on...",
"Bro...",
"Try again",
"I'm listening...",
"I don't understand :/"
]
IF/ELSE
statement to compare and match our arrays for a suitable reply or produce an alternate reply if we get a user input that does not match our userTexts
array.function output(input) {
if (compare(userTexts, botReplies, text)) {
// search for exact match in `userTexts`
finalResult = compare(userTexts, botReplies, text);
} else {
// if everything else fails, bot produces a random alternative reply
finalResult = alternative[Math.floor(Math.random() * alternative.length)];
}
// to update our HTML DOM element
addToChat(input, finalResult);
}
function compare(userTexts, botReplies, text) {
for (let x = 0; x < userTexts.length; x++) {
for (let y = 0; y < botReplies.length; y++){
if (userTexts[x][y] == text) {
let replies = botReplies[x];
let reply = replies[Math.floor(Math.random() * replies.length)];
}
}
}
return reply;
}
.appendChild
method, we could create a thread of messages by updating the user and chatbot field every time a message is sent.function addToChat(input, finalResult) {
let userDiv = document.createElement("div");
userDiv.id = "user";
userDiv.className = "response";
userDiv.innerHTML = `<span>${input}</span>
messagesContainer.appendChild(userDiv)`;
let botDiv = document.createElement("div");
let botImg = document.createElement("img");
let botText = document.createElement("span");
botDiv.id = "bot";
botImg.className = "avatar";
botDiv.className = "bot response";
botText.innerText = "Typing...";
botDiv.appendChild(botImg);
botDiv.appendChild(botText);
messagesContainer.appendChild(botDiv);
}