Client-Side Event Handling
Manage connection events like `open`, `message`, `error`, and `close` effectively in the browser.
Client-Side Event Handling is a free WebSockets & Realtime Systems Programming lesson on CoddyKit — lesson 3 of 4. You can read the complete lesson below for free — then practise it hands-on in the browser with a built-in code editor and a 24/7 AI tutor. It is part of the WebSockets & Realtime Systems Programming learning path, one of 4 lessons in the course, and your progress syncs across the web and the CoddyKit app.
Intro: Why Events Matter
WebSockets are dynamic! Unlike simple HTTP requests, a WebSocket connection stays open. This means you need a way to know when things happen on that connection.
That's where event handling comes in. It allows your browser application to react to the connection opening, messages arriving, errors, or the connection closing.
Connection Established: `onopen`
The first important event is open. This fires as soon as your WebSocket connection has been successfully established and is ready to send and receive data.
It's your green light to start communicating!
Handling Connection Open
Let's see how to handle the open event. When the connection is ready, a message is logged, and then we send a 'Hello' message.
const ws = new WebSocket('wss://echo.websocket.events');
ws.onopen = (event) => {
console.log('Connection established!');
ws.send('Hello WebSocket Server!');
};
// Other event handlers will be added laterReceiving Data: `onmessage`
Once connected, your server will send data. The message event is triggered every time your client receives data from the server.
The received data is in event.data. This can be text or binary data, which you might need to parse (e.g., JSON).
Processing Incoming Messages
Now, let's add an event listener for incoming messages. We'll log the data we receive back from the server.
const ws = new WebSocket('wss://echo.websocket.events');
ws.onopen = (event) => {
console.log('Connection established!');
ws.send('Hello WebSocket Server!');
};
ws.onmessage = (event) => {
console.log(`Server says: ${event.data}`);
};
// Other event handlers will be added laterCatching Errors: `onerror`
Things can go wrong! Network issues, server problems, or invalid protocols can trigger the error event. This event signals a problem but doesn't always provide specific error details directly.
Always include an error handler for robust applications.
Handling Connection Errors
Here's how to set up an onerror handler. This will catch general errors during the WebSocket connection's lifetime.
const ws = new WebSocket('wss://echo.websocket.events');
ws.onopen = (event) => {
console.log('Connection established!');
ws.send('Hello WebSocket Server!');
};
ws.onmessage = (event) => {
console.log(`Server says: ${event.data}`);
};
ws.onerror = (error) => {
console.error('WebSocket encountered an error!');
// More specific error details might be in the browser console
};
// Other event handlers will be added laterConnection Closed: `onclose`
When a WebSocket connection is deliberately closed by either the client or the server, the close event fires. It provides a code and a reason in the event object.
These details help you understand why the connection ended, which is crucial for debugging or attempting reconnections.
Responding to Connection Close
Let's add the onclose handler. It logs the closure code and reason, which are useful for understanding the connection's end.
const ws = new WebSocket('wss://echo.websocket.events');
ws.onopen = (event) => {
console.log('Connection established!');
ws.send('Hello WebSocket Server!');
};
ws.onmessage = (event) => {
console.log(`Server says: ${event.data}`);
};
ws.onerror = (error) => {
console.error('WebSocket encountered an error!');
};
ws.onclose = (event) => {
console.log(`Connection closed! Code: ${event.code}, Reason: ${event.reason || 'No reason provided'}`);
// Common codes: 1000 (normal), 1001 (going away), 1006 (abnormal closure)
};Event Handling Check
You've learned about the main WebSocket events. Now, let's test your understanding!
Recap: Mastering WebSocket Events
Great job! You've explored the essential client-side WebSocket events:
onopen: Fired when the connection is ready.onmessage: Handles incoming data from the server.onerror: Catches connection-related issues.onclose: Indicates the connection has terminated, providing a code and reason.
Understanding these events is key to building robust and interactive realtime applications!
Frequently asked questions
Is the “Client-Side Event Handling” lesson free?
Yes — the full text of “Client-Side Event Handling” is free to read here on the web, and the WebSockets & Realtime Systems Programming course includes 4 lessons in total. To practise it interactively (a built-in code editor and a 24/7 AI tutor) and unlock the rest of the WebSockets & Realtime Systems Programming course, upgrade to CoddyKit PRO.
What will I learn in “Client-Side Event Handling”?
Manage connection events like `open`, `message`, `error`, and `close` effectively in the browser. You practise WebSockets & Realtime Systems Programming with hands-on code you run directly in the browser, and a 24/7 AI tutor answers your questions as you work through the lesson.
Do I need any experience to start WebSockets & Realtime Systems Programming?
No prior experience is required. WebSockets & Realtime Systems Programming on CoddyKit is structured for beginners through advanced learners; this is — lesson 3 of 4, so you can start here or from the beginning and move at your own pace.
How long does the “Client-Side Event Handling” lesson take?
Most CoddyKit lessons take about 5–10 minutes. Each one is bite-sized and interactive, so you make steady progress and pick up exactly where you left off across the web and the app.
Can I write and run code in this WebSockets & Realtime Systems Programming lesson?
Yes. Every WebSockets & Realtime Systems Programming lesson includes a built-in code editor, so you write and run real code right in your browser and get instant AI feedback — no local setup required.
All lessons in this course
- Browser WebSocket API Fundamentals
- Sending and Receiving Data
- Client-Side Event Handling
- Automatic Reconnection on the Client