Lesson 15: Introduction to JavaScript Events
Learn how to handle user interactions with interactive examples and practical applications.
15.1 Understanding Events
Events are actions that trigger the execution of JavaScript code. They are usually triggered by web users. For example, clicking a mouse button, dragging the mouse over a hyperlink, or submitting a form are all events.
15.1.1 Common Form Events
Event | Description |
---|---|
onclick | Occurs when the user clicks a mouse button, checkbox, radio button, submit button or reset button |
onfocus | Occurs when the user clicks the mouse button or uses the tab to bring attention to a form element |
onselect | Occurs when the user selects text by dragging the mouse across it |
onblur | Occurs when the user removes focus from a currently focused form element |
onchange | Occurs when the user alters the input in form elements like text boxes |
onsubmit | Occurs when the user clicks the Submit button of a form |
15.2 onClick Event
The onClick event is one of the most commonly used events in JavaScript. It triggers when a user clicks on an element.
Example 15.1: Basic onClick Event
This example checks whether the user has entered text into a text box. If the text box is empty, it shows an alert.
// JavaScript function function checktext() { const textcontent = document.getElementById("mytext").value; if (textcontent === "") { alert("The textbox is empty, please write something!"); } else { document.getElementById("yourtext").innerHTML = textcontent; } } // HTML <input type="text" id="mytext" size="50"> <p>You have written "<span id="yourtext"></span>"</p> <input type="button" value="Check" onclick="checktext()">
You have written ""
15.2.1 Advanced onClick Event
Example 15.2: Dynamic Content Loading
This example shows how to use onClick to dynamically load content based on user selection.
// JavaScript function function loadContent() { const category = document.getElementById("category").value; const resultDiv = document.getElementById("result"); switch(category) { case "art": resultDiv.innerHTML = "Loading Art & Drawing content..."; break; case "tech": resultDiv.innerHTML = "Loading Technology content..."; break; case "sports": resultDiv.innerHTML = "Loading Sports content..."; break; default: resultDiv.innerHTML = "Select a category and click Load"; } } // HTML <select id="category"> <option value="">Select a category</option> <option value="art">Art & Drawing</option> <option value="tech">Technology</option> <option value="sports">Sports</option> </select> <button onclick="loadContent()">Load Content</button> <div id="result"></div>
15.3 Other Important Events
Explore more JavaScript events with interactive examples.
15.3.1 onFocus and onBlur Events
Example 15.3: Input Field Focus
These events trigger when an element gains or loses focus.
// JavaScript functions function handleFocus() { document.getElementById("focusBlurLog").innerHTML += "Field focused!\n"; document.getElementById("focusDemo").classList.add("focused"); } function handleBlur() { document.getElementById("focusBlurLog").innerHTML += "Field blurred!\n"; document.getElementById("focusDemo").classList.remove("focused"); } // HTML <input type="text" id="focusDemo" onfocus="handleFocus()" onblur="handleBlur()" placeholder="Click in and out of this field"> <div class="event-log" id="focusBlurLog"></div>
15.3.2 onSelect Event
Example 15.4: Text Selection
This event triggers when a user selects text in an input field.
// JavaScript function function handleSelect() { document.getElementById("selectLog").innerHTML += "Text selected!\n"; document.getElementById("selectDemo").classList.add("selected"); setTimeout(() => { document.getElementById("selectDemo").classList.remove("selected"); }, 1000); } // HTML <input type="text" id="selectDemo" onselect="handleSelect()" value="Try selecting some text"> <div class="event-log" id="selectLog"></div>
15.3.3 onChange Event
Example 15.5: Handling Input Changes
This event triggers when the value of an input element changes.
// JavaScript function function handleChange() { const color = document.getElementById("colorSelect").value; document.getElementById("changeDemo").style.backgroundColor = color; document.getElementById("changeLog").innerHTML += `Color changed to ${color}!\n`; } // HTML <select id="colorSelect" onchange="handleChange()"> <option value="#ffffff">White</option> <option value="#ffcccc">Red</option> <option value="#ccffcc">Green</option> <option value="#ccccff">Blue</option> </select> <div id="changeDemo" style="width:100%;height:100px;border:1px solid #ccc;margin-top:10px"></div> <div class="event-log" id="changeLog"></div>
15.3.4 onSubmit Event
Example 15.6: Form Submission Handling
This event triggers when a form is submitted, allowing validation before submission.
// JavaScript function function validateForm(event) { event.preventDefault(); // Prevent actual form submission const username = document.getElementById("username").value; const password = document.getElementById("password").value; if (username === "" || password === "") { document.getElementById("formResult").innerHTML = "Both fields are required!"; document.getElementById("formResult").style.color = "red"; } else { document.getElementById("formResult").innerHTML = "Form submitted successfully!"; document.getElementById("formResult").style.color = "green"; // In a real application, you would submit the form here } } // HTML <form onsubmit="validateForm(event)"> <input type="text" id="username" placeholder="Username"> <input type="password" id="password" placeholder="Password"> <button type="submit">Submit</button> </form> <div id="formResult"></div>
15.4 Real-World Applications
Events are used in virtually every JavaScript application. Here are practical examples:
Example 15.7: Interactive Task List
This application uses multiple events to create an interactive task manager.
// JavaScript functions
function addTask() {
const input = document.getElementById("taskInput");
const taskText = input.value.trim();
if (taskText !== "") {
const taskList = document.getElementById("taskList");
const newTask = document.createElement("li");
newTask.innerHTML = `
${taskText}
`;
taskList.appendChild(newTask);
input.value = "";
}
}
function completeTask(button) {
const task = button.parentElement;
task.classList.toggle("completed");
}
function deleteTask(button) {
const task = button.parentElement;
task.remove();
}
// HTML
<input type="text" id="taskInput" placeholder="Enter a new task">
<button onclick="addTask()">Add Task</button>
<ul id="taskList"></ul>