Creating a simple chatbot in JavaScript for a web page can be done with a mix of HTML, CSS, and JavaScript. Below is a basic example of a web page with a simple chatbot. This chatbot will respond with a predefined answer for a specific question and a default answer for any other questions.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Simple Chatbot</title>
<style>
#chatbox {
width: 300px;
height: 400px;
border: 1px solid #ccc;
padding: 10px;
overflow-y: scroll;
}
#userInput {
width: calc(100% - 22px);
margin-top: 10px;
}
</style>
</head>
<body>
<div id="chatbox">
<p><strong>Bot:</strong> Hi there! Ask me a question.</p>
</div>
<input type="text" id="userInput" placeholder="Ask me something...">
<button onclick="sendMsg()">Send</button>
<script>
function sendMsg() {
var input = document.getElementById('userInput');
var message = input.value;
input.value = '';
displayUserMsg(message);
getResponse(message);
}
function displayUserMsg(message) {
var chatbox = document.getElementById('chatbox');
chatbox.innerHTML += '<p><strong>You:</strong> ' + message + '</p>';
chatbox.scrollTop = chatbox.scrollHeight;
}
function displayBotMsg(message) {
var chatbox = document.getElementById('chatbox');
chatbox.innerHTML += '<p><strong>Bot:</strong> ' + message + '</p>';
chatbox.scrollTop = chatbox.scrollHeight;
}
function getResponse(message) {
var response = '';
if (message.toLowerCase() === 'hello') {
response = 'Hello! How can I help you today?';
} else {
response = 'Sorry, I am not sure how to respond to that.';
}
displayBotMsg(response);
}
</script>
</body>
</html>
This code snippet creates a simple chat interface with an input box and a send button. When the user types a message and clicks the send button, the message is displayed in the chatbox, and the getResponse function is called to generate a response from the chatbot.
The getResponse function has a very basic logic to respond with a specific message when the user says "hello" and with a default message for any other input.
To enhance this simple chatbot, you could implement more complex logic or even integrate it with a backend service that processes natural language to generate more intelligent responses.
Remember to save the code as an .html file and open it in a web browser to see the chatbot in action.