A chat app is the project that makes everything click: state, rendering, events, and the feeling of something alive on screen. This version is a front-end chat with a simulated friend — no server needed — and it teaches you the shape of every real chat app.
The plan
- A message list that grows as you send messages.
- An input and a send button (Enter works too).
- Messages styled differently for you and for the other person.
- A fake reply that arrives a second later, so the app feels alive.
The HTML
<div id="chat"></div>
<input id="input" type="text" placeholder="Type a message...">
<button id="send">Send</button>
The JavaScript
const chat = document.getElementById('chat');
const input = document.getElementById('input');
function addMessage(text, who) {
const div = document.createElement('div');
div.className = 'msg ' + who; // 'me' or 'them'
div.textContent = text;
chat.appendChild(div);
chat.scrollTop = chat.scrollHeight; // always show the newest message
}
function fakeReply() {
const replies = [
'That sounds great!',
'Tell me more.',
'Haha, exactly!',
'Let me think about that.'
];
setTimeout(() => {
addMessage(replies[Math.floor(Math.random() * replies.length)], 'them');
}, 1000);
}
function send() {
const text = input.value.trim();
if (!text) return;
addMessage(text, 'me');
input.value = '';
input.focus();
fakeReply();
}
document.getElementById('send').addEventListener('click', send);
input.addEventListener('keydown', (e) => {
if (e.key === 'Enter') send();
});
Three details beginners miss
-
Always scroll to the bottom after adding a message. Without
scrollTop = scrollHeight, new messages appear below the fold and the user thinks nothing happened. -
Never trust the input.
trim()and the empty check stop blank messages, andtextContent(notinnerHTML) stops a user from injecting HTML. -
Keep your own messages and theirs visually apart. One class for
me, one forthem, different alignment and colour. That single design choice is what makes it read as a chat instead of a list.
What to add next
A typing indicator ("... is typing"), timestamps, message history in localStorage, and — when you are ready — a real backend with WebSockets, so two browsers can talk to each other. A chat app is only as good as the conversations in it, so if you want to get better at real communication, not just the code, these best communication skills books for beginners are a good place to start.
Top comments (0)