Skip to content

Instantly share code, notes, and snippets.

@csr4mos
Created March 28, 2022 04:30
Show Gist options
  • Save csr4mos/a2710cd25d8331a456cd595199df5a35 to your computer and use it in GitHub Desktop.
Save csr4mos/a2710cd25d8331a456cd595199df5a35 to your computer and use it in GitHub Desktop.
Simple JavaScript Chatbot
<div id="output"></div>
<div id="container">
<input type="text" id="input" value="">
</div>
<!-- jquery for enter key press -->
<script src="https://code.jquery.com/jquery-3.0.0.js" integrity="sha256-jrPLZ+8vDxt2FnE1zvZXCkCcebI/C8Dt5xyaQBjxQIo=" crossorigin="anonymous"></script>
var questionNum = 0; // keep count of question, used for IF condition.
var question = '<h1>what is your name?</h1>'; // first question
var output = document.getElementById('output'); // store id="output" in output variable
output.innerHTML = question; // ouput first question
function bot() {
var input = document.getElementById("input").value;
console.log(input);
if (questionNum == 0) {
output.innerHTML = '<h1>hello ' + input + '</h1>';// output response
document.getElementById("input").value = ""; // clear text box
question = '<h1>how old are you?</h1>'; // load next question
setTimeout(timedQuestion, 2000); // output next question after 2sec delay
}
else if (questionNum == 1) {
output.innerHTML = '<h1>That means you were born in ' + (2016 - input) + '</h1>';
document.getElementById("input").value = "";
question = '<h1>where are you from?</h1>';
setTimeout(timedQuestion, 2000);
}
}
function timedQuestion() {
output.innerHTML = question;
}
//push enter key (using jquery), to run bot function.
$(document).keypress(function(e) {
if (e.which == 13) {
bot(); // run bot function when enter key pressed
questionNum++; // increase questionNum count by 1
}
});
* {
margin: 0;
padding: 0;
}
body {
background-color: #f0db4f;
}
h1, p {
font-family: sans-serif;
text-align: center;
color: #323330;
font-size: 100px;
}
p {
font-size: 30px;
}
#output, #container {
display: flex;
justify-content: center;
margin-top: 100px;
}
input {
background-color: #eee;
border: none;
font-family: sans-serif;
color: #000;
padding: 15px 32px;
text-align: center;
text-decoration: none;
display: inline-block;
font-size: 30px;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment