π Introduction to JavaScript's Event-Driven Architecture & The DOM
Lesson Overview
Before diving into working with APIs like JService, we first need to understand JavaScript's event-driven architecture and how it interacts with the Document Object Model (DOM).
In this lesson, we will cover:
- JavaScriptβs Event-Driven Architecture
- Understanding Asynchronous Programming
- How Events Work in JavaScript
- What is the DOM?
- Connecting JavaScript to an HTML File
- Practical Examples: Event Listeners & DOM Manipulation
By the end of this lesson, you will:
β
Understand how JavaScript handles events
β
Know how to manipulate the DOM dynamically
β
Be able to connect JavaScript to HTML & CSS
π Step 1: Understanding JavaScriptβs Event-Driven Architecture
JavaScript uses an event-driven model, which means that code execution is controlled by events (such as user actions like clicking a button or typing in a form).
πΉ What is an Event-Driven Architecture?
Think of JavaScript as a traffic cop ποΈπ¦:
- It listens for events (like cars approaching a red light).
- When an event occurs (like a pedestrian pressing a button), JavaScript reacts by running a function (like turning the light green).
- JavaScript keeps listening and responding without stopping other tasks.
πΉ Why Does This Matter?
- JavaScript can handle multiple tasks at the same time (asynchronous behavior).
- Your program can continue running other code instead of waiting for one task to finish.
- This makes web applications fast, smooth, and responsive.
π Step 2: Asynchronous Programming & The Event Loop
JavaScript is single-threaded, meaning it can only do one thing at a time. However, asynchronous programming allows it to handle multiple tasks without getting stuck.
πΉ Synchronous vs Asynchronous Code
- Synchronous: Code runs in order, one task at a time.
- Asynchronous: Code doesn't waitβit starts a task and moves on while waiting for it to complete.
πΉ Example of Asynchronous Behavior
console.log("Start");
setTimeout(() => {
console.log("This runs after 2 seconds!");
}, 2000);
console.log("End");Expected Output:
Start
End
This runs after 2 seconds!Even though we called setTimeout(), JavaScript doesnβt wait for it to finishβit moves on to console.log("End") first.
This is crucial for handling API calls, where we have to wait for data to return but still allow the rest of the code to execute.
π Step 3: Events in JavaScript
Events are actions like:
- Clicking a button (
click) - Typing in an input field (
input) - Submitting a form (
submit)
πΉ Adding Event Listeners
An event listener tells JavaScript to "listen" for an event and then run a function.
π Example: Click Event
document.getElementById("myButton").addEventListener("click", function() {
alert("Button Clicked!");
});document.getElementById("myButton")β Finds the button in HTML..addEventListener("click", function() { ... })β Listens for a click event.- When clicked, an alert message appears.
πΉ Common Event Types
| Event Type | Description |
|---|---|
click |
Fires when an element is clicked |
mouseover |
Fires when the mouse hovers over an element |
keydown |
Fires when a key is pressed |
input |
Fires when a user types in a field |
submit |
Fires when a form is submitted |
π Step 4: The Document Object Model (DOM)
The DOM (Document Object Model) is a map of an HTML document that JavaScript can use to find, modify, and interact with elements on a webpage.
πΉ Understanding the DOM Structure
Consider this simple HTML:
<!DOCTYPE html>
<html>
<head>
<title>My Page</title>
</head>
<body>
<h1 id="title">Hello, World!</h1>
<button id="myButton">Click Me</button>
<script src="script.js"></script>
</body>
</html>π οΈ JavaScript can manipulate this HTML using the DOM.
For example, if we want to change the <h1> content:
document.getElementById("title").innerText = "JavaScript is Amazing!";π Step 5: Connecting JavaScript to HTML
To make JavaScript work inside an HTML file, we need to link it.
πΉ Adding JavaScript to HTML
Inside the <head> of our HTML, we link the JavaScript file like this:
<head>
<title>My Web Page</title>
<link rel="stylesheet" href="style.css">
<script src="script.js" defer></script>
</head>src="script.js"β Points to the JavaScript file.deferβ Ensures the script loads after the HTML (so elements exist before JavaScript interacts with them).
π Step 6: Practical Examples
Letβs put this into action with event listeners & DOM manipulation.
π Example 1: Changing Text on Button Click
<!DOCTYPE html>
<html>
<head>
<title>Event Listener Example</title>
<script src="script.js" defer></script>
</head>
<body>
<h1 id="title">Click the button below</h1>
<button id="changeTextButton">Change Text</button>
</body>
</html>// script.js
document.getElementById("changeTextButton").addEventListener("click", function() {
document.getElementById("title").innerText = "You clicked the button!";
});π What Happens?
- The button listens for a click.
- When clicked, JavaScript updates the
<h1>text dynamically.
π Example 2: Changing Background Color
<body>
<button id="colorButton">Change Background</button>
</body>document.getElementById("colorButton").addEventListener("click", function() {
document.body.style.backgroundColor = "lightblue";
});π What Happens?
- Clicking the button changes the background color of the page.
π Example 3: User Input & Displaying Text
<body>
<input type="text" id="userInput" placeholder="Type something...">
<button id="displayButton">Display Text</button>
<p id="output"></p>
</body>document.getElementById("displayButton").addEventListener("click", function() {
let inputText = document.getElementById("userInput").value;
document.getElementById("output").innerText = inputText;
});π What Happens?
- User types something in the input box.
- Clicking the button displays the input in a
<p>tag.
π Step 7: Summary
Key Takeaways
β
JavaScript uses an event-driven model to respond to user interactions.
β
Events (click, input, etc.) trigger JavaScript functions.
β
The DOM allows JavaScript to interact with HTML elements.
β
Event Listeners wait for user actions & execute code dynamically.
π Now weβre ready to use these concepts in our next lesson: Fetching API Data with JavaScript!
