<?xml version="1.0" encoding="UTF-8"?>
<rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/"
    xmlns:atom="http://www.w3.org/2005/Atom" xmlns:media="http://search.yahoo.com/mrss/" version="2.0">
    <channel>
        
        <title>
            <![CDATA[ events - freeCodeCamp.org ]]>
        </title>
        <description>
            <![CDATA[ Browse thousands of programming tutorials written by experts. Learn Web Development, Data Science, DevOps, Security, and get developer career advice. ]]>
        </description>
        <link>https://www.freecodecamp.org/news/</link>
        <image>
            <url>https://cdn.freecodecamp.org/universal/favicons/favicon.png</url>
            <title>
                <![CDATA[ events - freeCodeCamp.org ]]>
            </title>
            <link>https://www.freecodecamp.org/news/</link>
        </image>
        <generator>Eleventy</generator>
        <lastBuildDate>Thu, 28 May 2026 20:56:57 +0000</lastBuildDate>
        <atom:link href="https://www.freecodecamp.org/news/tag/events/rss.xml" rel="self" type="application/rss+xml" />
        <ttl>60</ttl>
        
            <item>
                <title>
                    <![CDATA[ Event-Based Architectures in JavaScript: A Handbook for Devs ]]>
                </title>
                <description>
                    <![CDATA[ In modern software development, event-driven architectures have become one of the most powerful ways to build scalable, decoupled, and responsive systems. Instead of relying on direct calls between components, event-driven systems communicate through... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/event-based-architectures-in-javascript-a-handbook-for-devs/</link>
                <guid isPermaLink="false">690b87a7da01ae579df92085</guid>
                
                    <category>
                        <![CDATA[ software architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ event-driven-architecture ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ German Cocca ]]>
                </dc:creator>
                <pubDate>Wed, 05 Nov 2025 17:21:43 +0000</pubDate>
                <media:content url="https://cdn.hashnode.com/res/hashnode/image/upload/v1762296111539/a47bf1c2-1d4d-4c3b-8006-4f3479647f75.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In modern software development, <strong>event-driven architectures</strong> have become one of the most powerful ways to build scalable, decoupled, and responsive systems.</p>
<p>Instead of relying on direct calls between components, event-driven systems communicate through events – messages that signal that something has happened.</p>
<p>JavaScript, with its inherently asynchronous nature and built-in event loop, is a natural fit for this paradigm. From browser interactions to backend microservices, event-based communication enables flexibility, performance, and maintainability across the entire stack.</p>
<p>This handbook explores how event-driven architectures work, how they can be implemented in JavaScript (both in Node.js and in the browser), and why they are foundational to building modern distributed applications.</p>
<h3 id="heading-prerequisites-what-you-should-already-know">Prerequisites: What you should already know</h3>
<ul>
<li><p>JavaScript fundamentals (ES6+): modules, classes, closures, <code>this</code></p>
</li>
<li><p>Asynchronous JS: callbacks, Promises, <code>async</code>/<code>await</code>, and the event loop</p>
</li>
<li><p>Node.js basics</p>
</li>
</ul>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-introduction">1. Introduction</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-what-is-an-event-driven-architecture">What Is an Event-Driven Architecture?</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-why-javascript-naturally-fits-this-paradigm">Why JavaScript Naturally Fits This Paradigm</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-event-driven-vs-request-driven-architectures">Event-Driven vs. Request-Driven Architectures</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-it-makes-sense-to-use-an-event-driven-architecture">When It Makes Sense to Use an Event-Driven Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-it-might-not-be-the-right-choice">When It Might Not Be the Right Choice</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-typical-business-use-cases">Typical Business Use Cases</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-2-fundamentals-of-the-event-model-in-javascript">2. Fundamentals of the Event Model in JavaScript</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-the-event-loop-task-queue-and-call-stack">The Event Loop, Task Queue, and Call Stack</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-eventemitter-and-the-pubsub-pattern">EventEmitter and the Pub/Sub Pattern</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-eventtarget-customevent-and-browser-events">EventTarget, CustomEvent, and Browser Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-putting-it-all-together">Putting It All Together</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-3-publishersubscriber-pubsub-pattern">3. Publisher–Subscriber (Pub/Sub) Pattern</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-concept-and-advantages-of-decoupling">Concept and Advantages of Decoupling</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-basic-implementation-in-plain-javascript">Basic Implementation in Plain JavaScript</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-limitations-and-when-to-use-a-library">Limitations and When to Use a Library</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-4-implementations-in-nodejs">4. Implementations in Node.js</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-how-to-use-the-native-events-module">How to Use the Native events Module</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-example-event-oriented-microservice">Real Example: Event-Oriented Microservice</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-error-handling-and-backpressure">Error Handling and Backpressure</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-how-to-build-an-event-bus-across-services">How to Build an Event Bus Across Services</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-1">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-5-event-driven-microservices-architecture">5. Event-Driven Microservices Architecture</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-asynchronous-communication-via-message-brokers">Asynchronous Communication via Message Brokers</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-order-inventory-notification-flow">Example: Order → Inventory → Notification Flow</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-designing-event-contracts-event-schemas">Designing Event Contracts (Event Schemas)</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-an-event-driven-microservice-architecture">When to Use an Event-Driven Microservice Architecture</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-2">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-6-frontend-applications-and-events">6. Frontend Applications and Events</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-custom-events-in-the-browser">Custom Events in the Browser</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-event-communication-in-modern-frameworks">Event Communication in Modern Frameworks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-real-time-architectures-websockets-and-server-sent-events">Real-Time Architectures: WebSockets and Server-Sent Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-3">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-7-event-sourcing-and-cqrs-command-query-responsibility-segregation">7. Event Sourcing and CQRS (Command Query Responsibility Segregation)</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-event-sourcing-the-core-idea">Event Sourcing: The Core Idea</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-example-reconstructing-state-from-events">Example: Reconstructing State from Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-cqrs-command-query-responsibility-segregation">CQRS: Command Query Responsibility Segregation</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-difference-between-event-sourcing-and-pubsub">Difference Between Event Sourcing and Pub/Sub</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-when-to-use-event-sourcing-and-cqrs">When to Use Event Sourcing and CQRS</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-4">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-8-benefits-and-challenges">8. Benefits and Challenges</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-benefits-of-eda">Benefits of EDA</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-challenges-of-eda">Challenges of EDA</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-5">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-9-real-world-use-cases">9. Real-World Use Cases</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-financial-and-banking-systems">1. Financial and Banking Systems</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-e-commerce-platforms">2. E-commerce Platforms</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-iot-and-sensor-networks">3. IoT and Sensor Networks</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-real-time-analytics-and-monitoring">4. Real-Time Analytics and Monitoring</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-social-networks-and-messaging-apps">5. Social Networks and Messaging Apps</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-workflow-automation-and-orchestration">6. Workflow Automation and Orchestration</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-summary-6">Summary</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-10-best-practices-and-conclusions">10. Best Practices and Conclusions</a></p>
<ul>
<li><p><a class="post-section-overview" href="#heading-1-version-and-validate-events">1. Version and Validate Events</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-2-design-for-idempotency">2. Design for Idempotency</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-3-keep-events-meaningful-and-self-contained">3. Keep Events Meaningful and Self-Contained</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-4-implement-robust-error-handling-and-dead-letter-queues">4. Implement Robust Error Handling and Dead-Letter Queues</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-5-ensure-observability-and-traceability">5. Ensure Observability and Traceability</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-6-use-patterns-for-reliability">6. Use Patterns for Reliability</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-7-choose-the-right-broker-for-the-job">7. Choose the Right Broker for the Job</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-8-balance-event-driven-and-request-driven-approaches">8. Balance Event-Driven and Request-Driven Approaches</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-9-educate-and-align-the-team">9. Educate and Align the Team</a></p>
</li>
<li><p><a class="post-section-overview" href="#heading-10-start-small-then-evolve">10. Start Small, Then Evolve</a></p>
</li>
</ul>
</li>
<li><p><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></p>
</li>
</ul>
<h2 id="heading-1-introduction">1. Introduction</h2>
<p>Software systems are becoming increasingly distributed, asynchronous, and complex. Traditional <strong>request–response</strong> architectures – where one component directly calls another and waits for a reply – often create tight coupling and limit scalability.</p>
<p>In contrast, <strong>event-driven architectures (EDA)</strong> embrace asynchrony by letting components communicate through events (messages that represent a change or an occurrence in the system). When an event happens (for example, <em>“Order Created”</em>), other parts of the system that care about that event can react to it independently, without knowing who triggered it or when.</p>
<p>This simple shift from <strong>commands</strong> to <strong>events</strong> has profound implications for scalability, resilience, and system design. It allows applications to evolve as loosely coupled collections of independent components that listen for and emit events, rather than monolithic blocks of code that depend directly on each other.</p>
<h3 id="heading-what-is-an-event-driven-architecture">What Is an Event-Driven Architecture?</h3>
<p>An event-driven architecture is a software design pattern where the flow of the program is determined by events. An <strong>event</strong> can be any significant change in state, like a user action, a message from another system, a sensor reading, or even an internal trigger like a database update.</p>
<p>In this model:</p>
<ul>
<li><p><strong>Producers</strong> (also called emitters or publishers) generate and broadcast events.</p>
</li>
<li><p><strong>Consumers</strong> (or listeners or subscribers) react to those events asynchronously.</p>
</li>
</ul>
<p>Unlike traditional request-driven systems, producers and consumers don’t directly call each other. Instead, they communicate through a <strong>mediator</strong> (like an event bus, queue, or topic), achieving loose coupling and higher flexibility.</p>
<h3 id="heading-why-javascript-naturally-fits-this-paradigm">Why JavaScript Naturally Fits This Paradigm</h3>
<p>JavaScript was built around an event-driven model from its very beginning. In the browser, every user interaction – clicks, scrolls, network responses – is handled through events. The <strong>event loop</strong>, <strong>callback queue</strong>, and <strong>non-blocking I/O</strong> make JavaScript particularly well-suited for systems where many things happen concurrently.</p>
<p>In Node.js, this model extends to the backend. The <code>EventEmitter</code> API, asynchronous I/O, and the single-threaded event loop allow developers to write scalable services that handle thousands of concurrent connections efficiently. This makes JavaScript a natural language for implementing and experimenting with event-driven systems across the full stack, from the UI to distributed microservices.</p>
<h3 id="heading-event-driven-vs-request-driven-architectures">Event-Driven vs. Request-Driven Architectures</h3>
<p>Here’s a quick summary of the main features and differences:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Request-Driven</td><td>Event-Driven</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Communication</strong></td><td>Direct, synchronous (A calls B)</td><td>Indirect, asynchronous (A emits event, B reacts)</td></tr>
<tr>
<td><strong>Coupling</strong></td><td>Tight (services know each other)</td><td>Loose (services only know event types)</td></tr>
<tr>
<td><strong>Scalability</strong></td><td>Limited by synchronous blocking</td><td>Naturally scalable with asynchronous flows</td></tr>
<tr>
<td><strong>Failure handling</strong></td><td>Errors propagate directly</td><td>Components fail independently</td></tr>
<tr>
<td><strong>Typical example</strong></td><td>REST API call chain</td><td>Message bus or event broker (Kafka, RabbitMQ)</td></tr>
</tbody>
</table>
</div><p>Event-driven systems tend to perform better in environments that require real-time updates, asynchronous workflows, or high concurrency, such as financial transaction systems, IoT platforms, and analytics pipelines.</p>
<p>But adopting an Event-Driven Architecture is not a universal solution. It introduces its own complexities and is best suited to problems where loose coupling, scalability, and reactivity are primary goals.</p>
<h3 id="heading-when-it-makes-sense-to-use-an-event-driven-architecture">When It Makes Sense to Use an Event-Driven Architecture</h3>
<ul>
<li><p><strong>Asynchronous or real-time requirements</strong>: When the system needs to react to changes instantly (for example, new data, user interactions, or external triggers).</p>
</li>
<li><p><strong>High scalability and resilience</strong>: When services must handle variable workloads independently, without blocking or waiting for each other.</p>
</li>
<li><p><strong>Microservices or distributed systems</strong>: When independent services must communicate without strong dependencies or shared state.</p>
</li>
<li><p><strong>Extensibility and flexibility</strong>: When you expect the system to evolve over time, adding new consumers without modifying existing producers.</p>
</li>
<li><p><strong>Data streaming or continuous processing</strong>: When the system processes streams of events (for example, telemetry, logs, or payments) rather than discrete requests.</p>
</li>
</ul>
<h3 id="heading-when-it-might-not-be-the-right-choice">When It Might <em>Not</em> Be the Right Choice</h3>
<ul>
<li><p><strong>Simple, synchronous applications</strong>: For small systems where interactions are linear (for example, a CRUD API or a small monolith), introducing an event bus may be unnecessary overhead.</p>
</li>
<li><p><strong>Strong consistency requirements</strong>; When the system must maintain a strict order of operations or immediate transactional integrity, asynchronous event flows can complicate data coherence.</p>
</li>
<li><p><strong>Limited observability or operational tooling</strong>: Debugging distributed events is harder – tracing and replaying events requires good logging and monitoring infrastructure.</p>
</li>
<li><p><strong>Team inexperience</strong>: If the development team is not familiar with asynchronous systems, event versioning, or message brokers, the cognitive load may outweigh the benefits.</p>
</li>
</ul>
<h3 id="heading-typical-business-use-cases">Typical Business Use Cases</h3>
<ol>
<li><p><strong>E-commerce platforms:</strong> Events like <em>OrderPlaced</em>, <em>PaymentProcessed</em>, <em>ItemShipped</em> trigger workflows across inventory, billing, and logistics services.</p>
</li>
<li><p><strong>Financial and banking systems:</strong> Real-time updates of transactions, fraud detection, and asynchronous settlement processing.</p>
</li>
<li><p><strong>IoT and telemetry processing:</strong> Devices emit data continuously. The backend aggregates, filters, and reacts to these events asynchronously.</p>
</li>
<li><p><strong>Streaming analytics and monitoring:</strong> Continuous event ingestion from applications or sensors to update dashboards and trigger alerts.</p>
</li>
<li><p><strong>Social networks and messaging apps:</strong> Notifications, chat updates, and activity feeds naturally map to event streams that multiple consumers can subscribe to.</p>
</li>
<li><p><strong>Workflow orchestration systems:</strong> Each step in a process (for example, document signed, email sent, approval granted) triggers subsequent actions automatically.</p>
</li>
</ol>
<p>Event-driven architectures change the way we think about program flow. Instead of pulling data or waiting for responses, components <strong>react</strong> to what’s happening in the system.</p>
<p>By leveraging JavaScript’s asynchronous foundations, like the event loop, promises, and non-blocking I/O, developers can build architectures that are more responsive, resilient, and scalable than traditional request-driven designs.</p>
<p>In the next section, we’ll dive deeper into how JavaScript’s event model works, exploring the event loop, the task queue, and the key mechanisms (like <code>EventEmitter</code>) that make this paradigm possible.</p>
<h2 id="heading-2-fundamentals-of-the-event-model-in-javascript">2. Fundamentals of the Event Model in JavaScript</h2>
<p>JavaScript is inherently event-driven. From its earliest days in the browser to its modern incarnation on the server with Node.js, the language has been designed to handle asynchronous operations gracefully through events – signals that something has happened.</p>
<p>Understanding how this works under the hood is essential before applying event-driven principles to large systems.</p>
<h3 id="heading-the-event-loop-task-queue-and-call-stack">The Event Loop, Task Queue, and Call Stack</h3>
<p>At the heart of JavaScript’s concurrency model lies the <strong>event loop</strong>, a mechanism that enables asynchronous, non-blocking behavior in a single-threaded environment.</p>
<p>Let’s break it down:</p>
<ol>
<li><p><strong>Call Stack</strong>: This is where JavaScript executes code line by line. Each function call creates a new frame on the stack.</p>
</li>
<li><p><strong>Task Queue (or Callback Queue)</strong>: When asynchronous operations finish (like a <code>setTimeout</code> or a network request), their callbacks are queued here for later execution.</p>
</li>
<li><p><strong>Event Loop</strong>: Constantly checks if the call stack is empty. When it is, the loop dequeues a task and pushes it onto the stack to execute.</p>
</li>
</ol>
<p>This cycle repeats indefinitely – hence the term <em>“event loop.”</em></p>
<pre><code class="lang-typescript"><span class="hljs-built_in">console</span>.log(<span class="hljs-string">"A"</span>);

<span class="hljs-built_in">setTimeout</span>(<span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"B"</span>);
}, <span class="hljs-number">0</span>);

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">"C"</span>);

<span class="hljs-comment">// Output:</span>
<span class="hljs-comment">// A</span>
<span class="hljs-comment">// C</span>
<span class="hljs-comment">// B</span>
</code></pre>
<p>Even though the timeout is <code>0</code>, the callback runs <strong>after</strong> the synchronous code because it’s queued in the task queue and executed only when the call stack is clear.</p>
<p>This model allows JavaScript to remain responsive and non-blocking, even while performing I/O operations or waiting for user input.</p>
<h3 id="heading-eventemitter-and-the-pubsub-pattern">EventEmitter and the Pub/Sub Pattern</h3>
<p>Node.js exposes its event-driven core through the <code>EventEmitter</code> class – one of its most fundamental building blocks.</p>
<p>An <code>EventEmitter</code> lets objects emit events and subscribe to them. This mechanism forms the foundation for countless Node.js APIs, from HTTP servers to file streams.</p>
<p>Here’s a simple example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-comment">// Subscriber (listener)</span>
emitter.on(<span class="hljs-string">'dataReceived'</span>, <span class="hljs-function">(<span class="hljs-params">data</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Data received: <span class="hljs-subst">${data}</span>`</span>);
});

<span class="hljs-comment">// Publisher (emitter)</span>
emitter.emit(<span class="hljs-string">'dataReceived'</span>, <span class="hljs-string">'User profile loaded'</span>);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-typescript">Data received: User profile loaded
</code></pre>
<p>Each event has:</p>
<ul>
<li><p>A <strong>name</strong> (string or symbol)</p>
</li>
<li><p>A set of <strong>listeners</strong> (functions) that react to it</p>
</li>
</ul>
<p>This is the classic <strong>Publisher–Subscriber</strong> pattern (Pub/Sub): components publish events, while others subscribe to react – without direct references to each other.</p>
<h3 id="heading-eventtarget-customevent-and-browser-events">EventTarget, CustomEvent, and Browser Events</h3>
<p>In the browser, the same concept exists through the <code>EventTarget</code> API. Every DOM element can listen for or dispatch events.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>);

button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button clicked!'</span>);
});
</code></pre>
<p>We can also create <strong>custom events</strong> to simulate our own event-driven behavior:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> userEvent = <span class="hljs-keyword">new</span> CustomEvent(<span class="hljs-string">'userLoggedIn'</span>, {
  detail: { name: <span class="hljs-string">'Alice'</span> }
});

<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'userLoggedIn'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Welcome, <span class="hljs-subst">${e.detail.name}</span>!`</span>);
});

<span class="hljs-built_in">document</span>.dispatchEvent(userEvent);
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-typescript">Welcome, Alice!
</code></pre>
<p>This lightweight mechanism allows front-end applications to coordinate behavior across components without tight coupling.</p>
<h3 id="heading-putting-it-all-together">Putting It All Together</h3>
<p>Whether in the browser or Node.js, JavaScript’s asynchronous runtime and event-driven APIs form a natural foundation for building reactive, modular, and scalable systems.</p>
<p>In Node.js, nearly everything is an event emitter – HTTP requests, streams, process signals, and even errors. In the browser, events are how users and systems interact through clicks, network responses, and state changes.</p>
<p>This unified model across client and server is what makes JavaScript uniquely powerful for implementing end-to-end event-driven architectures.</p>
<p>In the next section, we’ll explore the Pub/Sub pattern in depth: we’ll understand its advantages, pitfalls, and how to implement it cleanly in plain JavaScript before scaling up to distributed systems.</p>
<h2 id="heading-3-publishersubscriber-pubsub-pattern">3. Publisher–Subscriber (Pub/Sub) Pattern</h2>
<p>The Publisher–Subscriber pattern, often abbreviated as Pub/Sub, is one of the most common and powerful foundations of event-driven systems. It defines how components can communicate asynchronously without knowing each other directly – a principle known as <strong>loose coupling</strong>.</p>
<p>In a Pub/Sub model:</p>
<ul>
<li><p><strong>Publishers</strong> (or emitters) broadcast events.</p>
</li>
<li><p><strong>Subscribers</strong> (or listeners) register interest in those events.</p>
</li>
<li><p>A <strong>broker</strong> (or event bus) acts as a mediator between the two.</p>
</li>
</ul>
<p>This separation allows systems to evolve and scale independently: new subscribers can be added without changing the publishers, and vice versa.</p>
<h3 id="heading-concept-and-advantages-of-decoupling">Concept and Advantages of Decoupling</h3>
<p>In traditional architectures, one component often depends directly on another:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">processOrder</span>(<span class="hljs-params">order</span>) </span>{
  sendInvoice(order);
  notifyWarehouse(order);
}
</code></pre>
<p>Here, <code>processOrder</code> is tightly coupled to the functions it calls. If we later need to send a shipping confirmation or trigger analytics, we must modify <code>processOrder</code> again. This violates the <strong>Open/Closed Principle</strong> (open for extension, closed for modification).</p>
<p>In a Pub/Sub model, the same logic becomes event-driven:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> bus = <span class="hljs-keyword">new</span> EventEmitter();

bus.on(<span class="hljs-string">'order:created'</span>, sendInvoice);
bus.on(<span class="hljs-string">'order:created'</span>, notifyWarehouse);

bus.emit(<span class="hljs-string">'order:created'</span>, { id: <span class="hljs-number">42</span>, items: <span class="hljs-number">3</span> });
</code></pre>
<p>Now, <code>processOrder</code> doesn’t need to know who’s listening. It simply emits an event (<code>order:created</code>), and any number of subscribers can react to it – even ones that didn’t exist when the code was written.</p>
<p><strong>Advantages:</strong></p>
<ul>
<li><p>✅ <strong>Loose coupling</strong> between components</p>
</li>
<li><p>⚙️ <strong>Easier extensibility</strong>: add new behaviors by adding listeners</p>
</li>
<li><p>🚀 <strong>Parallel evolution</strong>: teams can work on producers and consumers independently</p>
</li>
<li><p>🧩 <strong>Greater testability</strong>: events can be simulated in isolation</p>
</li>
</ul>
<h3 id="heading-basic-implementation-in-plain-javascript">Basic Implementation in Plain JavaScript</h3>
<p>While Node.js provides a ready-to-use <code>EventEmitter</code>, you can easily build a minimal event bus in plain JavaScript. This helps illustrate the underlying logic:</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createEventBus</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-keyword">const</span> listeners = {};

  <span class="hljs-keyword">return</span> {
    subscribe(event, callback) {
      <span class="hljs-keyword">if</span> (!listeners[event]) listeners[event] = [];
      listeners[event].push(callback);
    },
    publish(event, data) {
      (listeners[event] || []).forEach(<span class="hljs-function">(<span class="hljs-params">callback</span>) =&gt;</span> callback(data));
    },
    unsubscribe(event, callback) {
      listeners[event] = (listeners[event] || []).filter(<span class="hljs-function">(<span class="hljs-params">cb</span>) =&gt;</span> cb !== callback);
    }
  };
}

<span class="hljs-comment">// Example usage</span>
<span class="hljs-keyword">const</span> bus = createEventBus();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onUserRegistered</span>(<span class="hljs-params">user</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Welcome, <span class="hljs-subst">${user.name}</span>!`</span>);
}

bus.subscribe(<span class="hljs-string">'user:registered'</span>, onUserRegistered);
bus.publish(<span class="hljs-string">'user:registered'</span>, { name: <span class="hljs-string">'Alice'</span> });
bus.unsubscribe(<span class="hljs-string">'user:registered'</span>, onUserRegistered);
</code></pre>
<p>This simple implementation already captures the essence of Pub/Sub:</p>
<ul>
<li><p>You can <strong>subscribe</strong> to an event.</p>
</li>
<li><p>You can <strong>publish</strong> events with data.</p>
</li>
<li><p>You can <strong>unsubscribe</strong> dynamically.</p>
</li>
</ul>
<h3 id="heading-limitations-and-when-to-use-a-library"><strong>Limitations and When to Use a Library</strong></h3>
<p>While the above implementation works for small-scale use, real-world systems often require:</p>
<ul>
<li><p>Wildcard or hierarchical event names (for example, <code>order.*</code> or <code>user.created</code>)</p>
</li>
<li><p>Asynchronous delivery (with message queues or brokers)</p>
</li>
<li><p>Error handling and retries</p>
</li>
<li><p>Event persistence or replay</p>
</li>
<li><p>Cross-process or distributed communication</p>
</li>
</ul>
<p>In those cases, using a dedicated library or broker is more appropriate.</p>
<p>Popular options include Node.js’s built-in <code>EventEmitter</code> for in-process events, <code>RxJS</code> for reactive programming and stream composition, and message brokers like RabbitMQ, Kafka, or Redis Streams for distributed, scalable architectures</p>
<p>Each of these tools extends the Pub/Sub model to handle larger scale, fault tolerance, and observability – essential features in modern distributed systems.</p>
<h3 id="heading-summary">Summary</h3>
<p>The Publisher–Subscriber pattern is the backbone of event-driven design. It transforms direct, synchronous function calls into indirect, asynchronous communications, allowing systems to evolve gracefully and handle change without friction.</p>
<p>In JavaScript, this pattern is everywhere – from browser DOM events to Node.js streams and microservice architectures.</p>
<p>In the next section, we’ll dive deeper into practical implementations in Node.js, exploring how the <code>events</code> module powers many of the platform’s most important features and how it can be extended to build robust, event-oriented systems.</p>
<h2 id="heading-4-implementations-in-nodejs">4. Implementations in Node.js</h2>
<p>Node.js was designed from the ground up around the <strong>event-driven paradigm</strong>. Its single-threaded, non-blocking I/O model allows it to handle thousands of concurrent operations efficiently – not by running code in parallel, but by reacting to events as they occur.</p>
<p>At the heart of this model lies the <code>events</code> module, which exposes the <code>EventEmitter</code> class used throughout Node’s core APIs, from HTTP servers to file streams.</p>
<h3 id="heading-how-to-use-the-native-events-module">How to Use the Native <code>events</code> Module</h3>
<p>The <code>EventEmitter</code> class provides a standard way to <strong>emit</strong> and <strong>listen for</strong> events within a Node.js process.<br>It’s a lightweight yet powerful abstraction for asynchronous communication between components.</p>
<p>Let’s look at a simple example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-comment">// Register an event listener</span>
emitter.on(<span class="hljs-string">'user:login'</span>, <span class="hljs-function">(<span class="hljs-params">user</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`User logged in: <span class="hljs-subst">${user.name}</span>`</span>);
});

<span class="hljs-comment">// Emit the event</span>
emitter.emit(<span class="hljs-string">'user:login'</span>, { name: <span class="hljs-string">'Alice'</span> });
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-typescript">User logged <span class="hljs-keyword">in</span>: Alice
</code></pre>
<p>Each <code>EventEmitter</code> instance maintains an internal map of event names to listener functions. Listeners can be added using <code>.on()</code> or <code>.once()</code> (for one-time execution), and events are triggered asynchronously with <code>.emit()</code>.</p>
<h3 id="heading-real-example-event-oriented-microservice">Real Example: Event-Oriented Microservice</h3>
<p>To see this in action, imagine a simplified order-processing microservice:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
<span class="hljs-keyword">const</span> bus = <span class="hljs-keyword">new</span> EventEmitter();

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createOrder</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Order created: <span class="hljs-subst">${order.id}</span>`</span>);
  bus.emit(<span class="hljs-string">'order:created'</span>, order);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendInvoice</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Invoice sent for order <span class="hljs-subst">${order.id}</span>`</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">updateInventory</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Inventory updated for order <span class="hljs-subst">${order.id}</span>`</span>);
}

<span class="hljs-comment">// Subscribe listeners</span>
bus.on(<span class="hljs-string">'order:created'</span>, sendInvoice);
bus.on(<span class="hljs-string">'order:created'</span>, updateInventory);

<span class="hljs-comment">// Simulate an order</span>
createOrder({ id: <span class="hljs-number">123</span>, items: [<span class="hljs-string">'Book'</span>, <span class="hljs-string">'Pen'</span>] });
</code></pre>
<p><strong>Output:</strong></p>
<pre><code class="lang-typescript">Order created: <span class="hljs-number">123</span>
Invoice sent <span class="hljs-keyword">for</span> order <span class="hljs-number">123</span>
Inventory updated <span class="hljs-keyword">for</span> order <span class="hljs-number">123</span>
</code></pre>
<p>Here, the microservice emits an <code>order:created</code> event whenever a new order is placed. Multiple listeners (invoice and inventory handlers) react independently – a miniature event-driven architecture in a single process.</p>
<p>This approach scales naturally as the system grows. New behaviors, like sending notifications or analytics tracking, can be added by simply subscribing new listeners.</p>
<h3 id="heading-error-handling-and-backpressure">Error Handling and Backpressure</h3>
<p>In event-driven systems, error management is crucial because unhandled exceptions inside event listeners can crash the entire Node.js process.</p>
<p>To prevent this, Node provides built-in mechanisms:</p>
<ol>
<li><p><strong>Error events</strong>: You can emit and handle errors explicitly.</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">const</span> EventEmitter = <span class="hljs-built_in">require</span>(<span class="hljs-string">'events'</span>);
 <span class="hljs-keyword">const</span> emitter = <span class="hljs-keyword">new</span> EventEmitter();

 emitter.on(<span class="hljs-string">'error'</span>, <span class="hljs-function">(<span class="hljs-params">err</span>) =&gt;</span> {
   <span class="hljs-built_in">console</span>.error(<span class="hljs-string">'An error occurred:'</span>, err.message);
 });

 emitter.emit(<span class="hljs-string">'error'</span>, <span class="hljs-keyword">new</span> <span class="hljs-built_in">Error</span>(<span class="hljs-string">'Database connection failed'</span>));
</code></pre>
<p> If an <code>'error'</code> event is emitted without at least one listener, Node.js will throw it as an uncaught exception and terminate the process.</p>
</li>
<li><p><strong>Backpressure management</strong>: In streaming scenarios, producers can emit data faster than consumers can handle.</p>
<p> Node.js Streams solve this through <strong>backpressure</strong>, where consumers signal when they are ready for more data.</p>
<pre><code class="lang-typescript"> <span class="hljs-keyword">const</span> fs = <span class="hljs-built_in">require</span>(<span class="hljs-string">'fs'</span>);
 <span class="hljs-keyword">const</span> readable = fs.createReadStream(<span class="hljs-string">'large-file.txt'</span>);
 <span class="hljs-keyword">const</span> writable = fs.createWriteStream(<span class="hljs-string">'copy.txt'</span>);

 readable.pipe(writable); <span class="hljs-comment">// Automatically manages flow control</span>
</code></pre>
<p> Under the hood, streams use event-based coordination (<code>data</code>, <code>drain</code>, <code>end</code>) to ensure stability even under heavy load.</p>
</li>
</ol>
<h3 id="heading-how-to-build-an-event-bus-across-services">How to Build an Event Bus Across Services</h3>
<p>While <code>EventEmitter</code> works within a single process, real-world architectures often span multiple microservices or containers. In such cases, an external message broker (like RabbitMQ, Kafka, or Redis Streams) acts as a distributed event bus.</p>
<p>Each service becomes either:</p>
<ul>
<li><p>a <strong>producer</strong> (publishing events), or</p>
</li>
<li><p>a <strong>consumer</strong> (subscribing and reacting).</p>
</li>
</ul>
<p>Node.js integrates seamlessly with these systems using community libraries:</p>
<ul>
<li><p><a target="_blank" href="https://www.npmjs.com/package/amqplib"><code>amqplib</code></a> for RabbitMQ</p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/kafkajs"><code>kafkajs</code></a> for Apache Kafka</p>
</li>
<li><p><a target="_blank" href="https://www.npmjs.com/package/redis"><code>redis</code></a> for Redis Pub/Sub</p>
</li>
</ul>
<p>Example (simplified with Redis):</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> { createClient } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'redis'</span>);
<span class="hljs-keyword">const</span> publisher = createClient();
<span class="hljs-keyword">const</span> subscriber = createClient();

<span class="hljs-keyword">await</span> publisher.connect();
<span class="hljs-keyword">await</span> subscriber.connect();

subscriber.subscribe(<span class="hljs-string">'user:created'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`New user event received: <span class="hljs-subst">${message}</span>`</span>);
});

<span class="hljs-keyword">await</span> publisher.publish(<span class="hljs-string">'user:created'</span>, <span class="hljs-built_in">JSON</span>.stringify({ id: <span class="hljs-number">1</span>, name: <span class="hljs-string">'Alice'</span> }));
</code></pre>
<p>This pattern allows <strong>cross-service communication</strong> without tight coupling. Each service reacts to events asynchronously, whether it’s hosted locally or across a cluster.</p>
<h3 id="heading-summary-1">Summary</h3>
<p>The Node.js <code>EventEmitter</code> encapsulates the essence of event-driven design at the process level: lightweight, decoupled, and asynchronous. Combined with external message brokers, it becomes a powerful tool for building scalable, distributed event-driven systems.</p>
<p>Through events, Node.js applications can handle multiple concurrent workflows efficiently, maintain clear separation of concerns, and grow organically as the system evolves.</p>
<p>In the next section, we’ll extend this idea beyond a single application. We’ll explore <strong>Event-Driven Microservices Architecture</strong>, where multiple independent services communicate entirely through asynchronous event flows.</p>
<h2 id="heading-5-event-driven-microservices-architecture">5. Event-Driven Microservices Architecture</h2>
<p>As applications grow, a single event bus inside one process is no longer enough. When your system consists of multiple independently deployed services – each owning its own data and responsibilities – the Event-Driven Architecture becomes a natural fit for enabling asynchronous, decoupled communication.</p>
<p>In an event-driven microservice ecosystem, services don’t call each other directly through HTTP or RPC.<br>Instead, they publish and consume events through a <strong>message broker</strong> – a central medium that handles delivery, queuing, and persistence of messages between services.</p>
<h3 id="heading-asynchronous-communication-via-message-brokers">Asynchronous Communication via Message Brokers</h3>
<p>In a request-driven microservice system, one service directly invokes another via REST or gRPC:</p>
<pre><code class="lang-typescript">Order Service  →  Inventory Service  →  Notification Service
</code></pre>
<p>Each call is synchronous, meaning the caller waits for a response. This creates coupling and potential cascading failures if one service is down or slow.</p>
<p>In an event-driven model, communication happens asynchronously through events:</p>
<pre><code class="lang-typescript">Order Service  →  [Event Bus]  →  Inventory Service, Notification Service
</code></pre>
<p>The event bus becomes the backbone of the system. Each service publishes events and subscribes to those it needs, without knowing who will consume them.</p>
<p>This brings several advantages:</p>
<ul>
<li><p>⚙️ <strong>Loose coupling:</strong> services don’t depend on each other’s availability</p>
</li>
<li><p>📈 <strong>Scalability:</strong> new consumers can subscribe without changing existing code</p>
</li>
<li><p>🔁 <strong>Resilience:</strong> temporary outages are absorbed by the broker’s queues</p>
</li>
<li><p>🧩 <strong>Extensibility:</strong> new workflows can be added just by listening to existing events</p>
</li>
</ul>
<h3 id="heading-example-order-inventory-notification-flow">Example: Order → Inventory → Notification Flow</h3>
<p>Let’s consider a practical scenario in an e-commerce platform:</p>
<ol>
<li><p><strong>Order Service</strong> publishes an <code>order:created</code> event when a user places an order.</p>
</li>
<li><p><strong>Inventory Service</strong> subscribes to <code>order:created</code> and decrements stock.</p>
</li>
<li><p><strong>Notification Service</strong> also subscribes to <code>order:created</code> and sends a confirmation email.</p>
</li>
</ol>
<pre><code class="lang-typescript">          ┌──────────────────────┐
          │   Order Service      │
          │ emits <span class="hljs-string">"order:created"</span>│
          └──────────┬───────────┘
                     │
          ┌──────────▼───────────┐
          │     Event Bus        │
          │ (Kafka, RabbitMQ...) │
          └──────┬───────────────┘
      ┌──────────┴───────────┐   ┌────────────────────┐
      │ Inventory Service    │   │ Notification Service│
      │ updates stock        │   │ sends email         │
      └──────────────────────┘   └────────────────────┘
</code></pre>
<p><strong>Node.js example (simplified with Redis):</strong></p>
<pre><code class="lang-typescript"><span class="hljs-comment">// order-service.js</span>
<span class="hljs-keyword">const</span> { createClient } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'redis'</span>);
<span class="hljs-keyword">const</span> publisher = createClient();
<span class="hljs-keyword">await</span> publisher.connect();

<span class="hljs-keyword">async</span> <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">createOrder</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Order created: <span class="hljs-subst">${order.id}</span>`</span>);
  <span class="hljs-keyword">await</span> publisher.publish(<span class="hljs-string">'order:created'</span>, <span class="hljs-built_in">JSON</span>.stringify(order));
}

createOrder({ id: <span class="hljs-number">42</span>, items: [<span class="hljs-string">'Book'</span>, <span class="hljs-string">'Pen'</span>] });
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// inventory-service.js</span>
<span class="hljs-keyword">const</span> { createClient } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'redis'</span>);
<span class="hljs-keyword">const</span> subscriber = createClient();
<span class="hljs-keyword">await</span> subscriber.connect();

<span class="hljs-keyword">await</span> subscriber.subscribe(<span class="hljs-string">'order:created'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> order = <span class="hljs-built_in">JSON</span>.parse(message);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Updating inventory for order <span class="hljs-subst">${order.id}</span>`</span>);
});
</code></pre>
<pre><code class="lang-typescript"><span class="hljs-comment">// notification-service.js</span>
<span class="hljs-keyword">const</span> { createClient } = <span class="hljs-built_in">require</span>(<span class="hljs-string">'redis'</span>);
<span class="hljs-keyword">const</span> subscriber = createClient();
<span class="hljs-keyword">await</span> subscriber.connect();

<span class="hljs-keyword">await</span> subscriber.subscribe(<span class="hljs-string">'order:created'</span>, <span class="hljs-function">(<span class="hljs-params">message</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> order = <span class="hljs-built_in">JSON</span>.parse(message);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Sending confirmation email for order <span class="hljs-subst">${order.id}</span>`</span>);
});
</code></pre>
<p>Each service is now independent. They communicate only through <strong>events</strong>, not direct calls.</p>
<h3 id="heading-designing-event-contracts-event-schemas">Designing Event Contracts (Event Schemas)</h3>
<p>In a distributed system, events are <strong>contracts</strong> – they define what information producers share and consumers rely on. Defining and maintaining these contracts carefully is crucial to avoid breaking downstream consumers.</p>
<p>A good event should:</p>
<ul>
<li><p>Contain enough context for consumers to act independently</p>
</li>
<li><p>Use a <strong>versioned schema</strong> to evolve safely over time</p>
</li>
<li><p>Include metadata like <code>eventId</code>, <code>timestamp</code>, and <code>source</code></p>
</li>
</ul>
<p><strong>Example event schema (JSON):</strong></p>
<pre><code class="lang-typescript">{
  <span class="hljs-string">"event"</span>: <span class="hljs-string">"order:created"</span>,
  <span class="hljs-string">"version"</span>: <span class="hljs-number">1</span>,
  <span class="hljs-string">"timestamp"</span>: <span class="hljs-string">"2025-10-29T18:45:00Z"</span>,
  <span class="hljs-string">"data"</span>: {
    <span class="hljs-string">"orderId"</span>: <span class="hljs-number">42</span>,
    <span class="hljs-string">"userId"</span>: <span class="hljs-number">123</span>,
    <span class="hljs-string">"items"</span>: [
      { <span class="hljs-string">"sku"</span>: <span class="hljs-string">"BOOK-001"</span>, <span class="hljs-string">"quantity"</span>: <span class="hljs-number">2</span> },
      { <span class="hljs-string">"sku"</span>: <span class="hljs-string">"PEN-003"</span>, <span class="hljs-string">"quantity"</span>: <span class="hljs-number">1</span> }
    ],
    <span class="hljs-string">"total"</span>: <span class="hljs-number">39.90</span>
  }
}
</code></pre>
<p>Best practices:</p>
<ul>
<li><p>Use namespaced event types (<code>order:created</code>, <code>payment:failed</code>)</p>
</li>
<li><p>Include a version number (<code>v1</code>, <code>v2</code>) to avoid schema drift</p>
</li>
<li><p>Store events in a central registry (for example, JSON Schema repository)</p>
</li>
<li><p>Log all events for auditing and debugging</p>
</li>
</ul>
<h3 id="heading-when-to-use-an-event-driven-microservice-architecture">When to Use an Event-Driven Microservice Architecture</h3>
<p>Event-driven microservices are especially valuable when:</p>
<ul>
<li><p>Systems require real-time updates (for example, notifications, analytics)</p>
</li>
<li><p>Components must operate independently and asynchronously</p>
</li>
<li><p>The platform needs to scale horizontally across services</p>
</li>
<li><p>New capabilities should be added without touching existing code</p>
</li>
</ul>
<p>But this architecture also brings challenges:</p>
<ul>
<li><p>Harder to trace flows across multiple asynchronous hops</p>
</li>
<li><p>Requires observability tools (logs, traces, metrics) to debug issues</p>
</li>
<li><p>Event ordering and exact-once delivery can be complex</p>
</li>
<li><p>Increased operational overhead from managing brokers and message queues</p>
</li>
</ul>
<h3 id="heading-summary-2">Summary</h3>
<p>Event-driven microservices take the principles of the Pub/Sub pattern and scale them across distributed systems. By communicating exclusively through asynchronous events, services become autonomous, resilient, and extensible. This is ideal for modern cloud architectures and high-throughput applications.</p>
<p>In the next section, we’ll shift our focus to the front end and explore how event-driven principles power reactivity in browsers and frameworks like React and Vue, and how technologies like <strong>WebSockets</strong> and <strong>Server-Sent Events</strong> enable real-time user experiences.</p>
<h2 id="heading-6-frontend-applications-and-events">6. Frontend Applications and Events</h2>
<p>While backend systems use event-driven architectures to coordinate between services, frontend applications have relied on event-based programming since JavaScript’s creation. And again, every user interaction is handled through events.</p>
<p>Understanding how events flow in the browser, and how modern frameworks like React and Vue build upon this model, is key to creating responsive, decoupled, and real-time user interfaces.</p>
<h3 id="heading-custom-events-in-the-browser">Custom Events in the Browser</h3>
<p>In vanilla JavaScript, every DOM element can emit and listen to events through the <code>EventTarget</code> API.<br>This mechanism is the foundation of how browsers handle user interaction and component communication.</p>
<p><strong>Example – Basic Event Handling:</strong></p>
<pre><code class="lang-typescript">&lt;button id=<span class="hljs-string">"subscribeBtn"</span>&gt;Subscribe&lt;/button&gt;
&lt;script&gt;
  <span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'subscribeBtn'</span>);
  btn.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User subscribed!'</span>);
  });
&lt;/script&gt;
</code></pre>
<p>Here, the button acts as an <strong>event emitter</strong>. When the <code>click</code> event occurs, the listener function reacts. This is a simple example of publish-subscribe behavior within the DOM.</p>
<p>You can also define <strong>custom events</strong> to allow decoupled communication between components:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> userEvent = <span class="hljs-keyword">new</span> CustomEvent(<span class="hljs-string">'user:registered'</span>, {
  detail: { name: <span class="hljs-string">'Alice'</span>, email: <span class="hljs-string">'alice@example.com'</span> }
});

<span class="hljs-comment">// Listen for the event</span>
<span class="hljs-built_in">document</span>.addEventListener(<span class="hljs-string">'user:registered'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Welcome <span class="hljs-subst">${e.detail.name}</span>!`</span>);
});

<span class="hljs-comment">// Dispatch it</span>
<span class="hljs-built_in">document</span>.dispatchEvent(userEvent);
</code></pre>
<p>Output:</p>
<pre><code class="lang-typescript">Welcome Alice!
</code></pre>
<p>This approach allows different parts of the UI to react to user actions or system changes without directly calling each other.</p>
<h3 id="heading-event-communication-in-modern-frameworks">Event Communication in Modern Frameworks</h3>
<p>Modern JavaScript frameworks like React, Vue, and Angular abstract the native event system, but the core idea remains the same: <strong>components react to events</strong>.</p>
<h4 id="heading-react-example">React Example</h4>
<p>React’s synthetic event system wraps the browser’s native events, providing a unified interface across browsers.</p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">NewsletterSignup</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleSubmit</span>(<span class="hljs-params">e</span>) </span>{
    e.preventDefault();
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Newsletter form submitted!'</span>);
  }

  <span class="hljs-keyword">return</span> (
    &lt;form onSubmit={handleSubmit}&gt;
      &lt;input <span class="hljs-keyword">type</span>=<span class="hljs-string">"email"</span> placeholder=<span class="hljs-string">"Your email"</span> /&gt;
      &lt;button <span class="hljs-keyword">type</span>=<span class="hljs-string">"submit"</span>&gt;Subscribe&lt;/button&gt;
    &lt;/form&gt;
  );
}
</code></pre>
<p>Behind the scenes, React uses an <strong>event delegation</strong> model: it attaches a single listener at the root and dispatches events down the component tree efficiently.</p>
<p>For cross-component communication, React developers often use:</p>
<ul>
<li><p>Context or state managers (like Redux, Zustand, or Recoil)</p>
</li>
<li><p>Event emitter utilities (like <code>mitt</code> or <code>nanoevents</code>)</p>
</li>
<li><p>Custom hooks for modular event handling</p>
</li>
</ul>
<p>Example using a lightweight emitter (<code>mitt</code>):</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">import</span> mitt <span class="hljs-keyword">from</span> <span class="hljs-string">'mitt'</span>;

<span class="hljs-keyword">export</span> <span class="hljs-keyword">const</span> bus = mitt();
</code></pre>
<p>Then anywhere in your app:</p>
<pre><code class="lang-typescript"><span class="hljs-comment">// Component A</span>
bus.emit(<span class="hljs-string">'theme:changed'</span>, <span class="hljs-string">'dark'</span>);

<span class="hljs-comment">// Component B</span>
bus.on(<span class="hljs-string">'theme:changed'</span>, <span class="hljs-function">(<span class="hljs-params">theme</span>) =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">`Theme updated to <span class="hljs-subst">${theme}</span>`</span>);
});
</code></pre>
<p>This simple event bus decouples components that don’t share a direct parent-child relationship.</p>
<h4 id="heading-vue-example">Vue Example</h4>
<p>Vue provides a native event system for <strong>child-to-parent</strong> communication and also supports global event buses.</p>
<pre><code class="lang-typescript">&lt;template&gt;
  &lt;button <span class="hljs-meta">@click</span>=<span class="hljs-string">"notify"</span>&gt;Notify Parent&lt;/button&gt;
&lt;/template&gt;

&lt;script&gt;
<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> {
  methods: {
    notify() {
      <span class="hljs-built_in">this</span>.$emit(<span class="hljs-string">'user-registered'</span>, { name: <span class="hljs-string">'Alice'</span> });
    }
  }
};
&lt;/script&gt;
</code></pre>
<p>The parent component can listen for <code>user-registered</code> and react accordingly. Vue 3 also supports custom event buses via external libraries like <code>mitt</code>, enabling component-to-component events without tight coupling.</p>
<h3 id="heading-real-time-architectures-websockets-and-server-sent-events">Real-Time Architectures: WebSockets and Server-Sent Events</h3>
<p>In modern web applications, the event-driven model extends beyond the client, connecting the front end and back end in real-time.</p>
<h4 id="heading-websockets">WebSockets</h4>
<p>WebSockets provide a full-duplex channel between the browser and the server. This means both sides can send events at any time, enabling instant updates without polling.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> socket = <span class="hljs-keyword">new</span> WebSocket(<span class="hljs-string">'wss://example.com/socket'</span>);

socket.addEventListener(<span class="hljs-string">'open'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Connected to server'</span>);
  socket.send(<span class="hljs-built_in">JSON</span>.stringify({ event: <span class="hljs-string">'user:joined'</span>, name: <span class="hljs-string">'Alice'</span> }));
});

socket.addEventListener(<span class="hljs-string">'message'</span>, <span class="hljs-function">(<span class="hljs-params">msg</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(msg.data);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'New event from server:'</span>, data);
});
</code></pre>
<p>Use cases:</p>
<ul>
<li><p>Real-time chat applications</p>
</li>
<li><p>Live dashboards</p>
</li>
<li><p>Online multiplayer games</p>
</li>
</ul>
<h4 id="heading-server-sent-events-sse">Server-Sent Events (SSE)</h4>
<p>SSE is a simpler alternative when you only need one-way communication – from server to client – using standard HTTP connections.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> source = <span class="hljs-keyword">new</span> EventSource(<span class="hljs-string">'/events'</span>);

source.addEventListener(<span class="hljs-string">'update'</span>, <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
  <span class="hljs-keyword">const</span> data = <span class="hljs-built_in">JSON</span>.parse(e.data);
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Received update:'</span>, data);
});
</code></pre>
<p>SSE is ideal for live notifications, monitoring dashboards, and continuous data feeds.</p>
<h3 id="heading-summary-3">Summary</h3>
<p>The frontend world has always been event-driven – from DOM interactions to modern component frameworks and real-time connections.</p>
<p>By treating the UI as a system that <strong>reacts to events rather than polling for changes</strong>, we build interfaces that are more responsive, more modular, and easier to extend and integrate with event-driven back ends.</p>
<p>Whether you use <code>CustomEvent</code>, <code>mitt</code>, WebSockets, or SSE, the principle is the same: emit events, listen for changes, and let your app respond asynchronously.</p>
<p>In the next section, we’ll explore how these same principles extend into Event Sourcing and CQRS (Command Query Responsibility Segregation) – advanced architectural patterns that persist and reconstruct system state entirely through events.</p>
<h2 id="heading-7-event-sourcing-and-cqrs-command-query-responsibility-segregation">7. Event Sourcing and CQRS (Command Query Responsibility Segregation)</h2>
<p>Up to this point, we’ve explored events as <strong>transient messages</strong> that trigger behavior – signals passed between components or services. But in more advanced architectures, events can also become the source of truth for the system’s state itself.</p>
<p>This is where <strong>Event Sourcing</strong> and <strong>CQRS</strong> come into play.</p>
<p>These patterns are fundamental in systems that require auditability, replayability, and scalable state reconstruction, such as banking platforms, e-commerce systems, and workflow engines.</p>
<h3 id="heading-event-sourcing-the-core-idea">Event Sourcing: The Core Idea</h3>
<p>In traditional architectures, a system stores only the current state: for example, a database row representing the latest balance of a user’s account.</p>
<p>In Event Sourcing, the system instead stores a series of events that led to that state. Each event represents a historical change, such as <code>AccountCreated</code>, <code>FundsDeposited</code>, or <code>FundsWithdrawn</code>.</p>
<p>When you need the current state, you don’t query a static record – you <strong>replay</strong> all relevant events in sequence.</p>
<p><strong>Traditional Model:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Account</td><td>Balance</td></tr>
</thead>
<tbody>
<tr>
<td>#001</td><td>$500</td></tr>
</tbody>
</table>
</div><p><strong>Event-Sourced Model:</strong></p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Timestamp</td><td>Event</td><td>Data</td></tr>
</thead>
<tbody>
<tr>
<td>10:00 AM</td><td>AccountCreated</td><td>{ id: 1, owner: 'Alice' }</td></tr>
<tr>
<td>10:05 AM</td><td>FundsDeposited</td><td>{ id: 1, amount: 300 }</td></tr>
<tr>
<td>10:10 AM</td><td>FundsDeposited</td><td>{ id: 1, amount: 200 }</td></tr>
</tbody>
</table>
</div><p>To calculate the balance, you replay the events:</p>
<pre><code class="lang-typescript"><span class="hljs-number">0</span> + <span class="hljs-number">300</span> + <span class="hljs-number">200</span> = $<span class="hljs-number">500</span>
</code></pre>
<p>This approach provides:</p>
<ul>
<li><p>🧾 <strong>Full audit history</strong>: every state change is recorded</p>
</li>
<li><p>🔁 <strong>Replayability</strong>: rebuild state after crashes or schema changes</p>
</li>
<li><p>🧩 <strong>Temporal queries</strong>: know what the system looked like at any point in time</p>
</li>
</ul>
<h3 id="heading-example-reconstructing-state-from-events">Example: Reconstructing State from Events</h3>
<p>Let’s illustrate with a simple JavaScript implementation.</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">const</span> events = [
  { <span class="hljs-keyword">type</span>: <span class="hljs-string">'AccountCreated'</span>, data: { id: <span class="hljs-number">1</span>, owner: <span class="hljs-string">'Alice'</span> } },
  { <span class="hljs-keyword">type</span>: <span class="hljs-string">'FundsDeposited'</span>, data: { id: <span class="hljs-number">1</span>, amount: <span class="hljs-number">300</span> } },
  { <span class="hljs-keyword">type</span>: <span class="hljs-string">'FundsDeposited'</span>, data: { id: <span class="hljs-number">1</span>, amount: <span class="hljs-number">200</span> } },
  { <span class="hljs-keyword">type</span>: <span class="hljs-string">'FundsWithdrawn'</span>, data: { id: <span class="hljs-number">1</span>, amount: <span class="hljs-number">100</span> } }
];

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">rebuildAccount</span>(<span class="hljs-params">events</span>) </span>{
  <span class="hljs-keyword">let</span> balance = <span class="hljs-number">0</span>;

  <span class="hljs-keyword">for</span> (<span class="hljs-keyword">const</span> event <span class="hljs-keyword">of</span> events) {
    <span class="hljs-keyword">switch</span> (event.type) {
      <span class="hljs-keyword">case</span> <span class="hljs-string">'FundsDeposited'</span>:
        balance += event.data.amount;
        <span class="hljs-keyword">break</span>;
      <span class="hljs-keyword">case</span> <span class="hljs-string">'FundsWithdrawn'</span>:
        balance -= event.data.amount;
        <span class="hljs-keyword">break</span>;
    }
  }

  <span class="hljs-keyword">return</span> balance;
}

<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Current balance:'</span>, rebuildAccount(events)); <span class="hljs-comment">// 400</span>
</code></pre>
<p>Here, we never stored a static “balance” field. Instead, we <strong>reconstructed</strong> it from the sequence of past events – the same way a ledger works in accounting.</p>
<p>This technique is powerful for debugging, auditing, or migrating systems: you can replay all events in a new environment to rebuild state exactly as it was.</p>
<h3 id="heading-cqrs-command-query-responsibility-segregation">CQRS: Command Query Responsibility Segregation</h3>
<p><strong>CQRS (Command Query Responsibility Segregation)</strong> is a complementary pattern often used with Event Sourcing.<br>It separates the model for writing data (commands) from the model for reading data (queries).</p>
<ul>
<li><p><strong>Commands</strong> modify system state by producing events (<code>OrderPlaced</code>, <code>PaymentProcessed</code>).</p>
</li>
<li><p><strong>Queries</strong> read data optimized for retrieval (for example, a denormalized “view” of orders).</p>
</li>
</ul>
<p>This separation improves scalability and performance because the read and write sides can evolve independently – even use different databases.</p>
<p><strong>Simplified diagram:</strong></p>
<pre><code class="lang-typescript">[User Action]
      │
      ▼
 ┌────────────┐
 │ Command API│  ---&gt;  emits ---&gt;  [Event Store]
 └────────────┘                      │
                                    ▼
                        ┌────────────────────┐
                        │  Read Model / View │
                        │ (e.g., MongoDB)    │
                        └────────────────────┘
</code></pre>
<p><strong>Example (conceptual):</strong></p>
<pre><code class="lang-typescript"><span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">placeOrder</span>(<span class="hljs-params">order</span>) </span>{
  <span class="hljs-comment">// Write model</span>
  eventStore.push({ <span class="hljs-keyword">type</span>: <span class="hljs-string">'OrderPlaced'</span>, data: order });
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">getOrdersView</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-comment">// Read model</span>
  <span class="hljs-keyword">return</span> eventStore
    .filter(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> e.type === <span class="hljs-string">'OrderPlaced'</span>)
    .map(<span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> e.data);
}
</code></pre>
<p>Here, the <strong>event store</strong> acts as the single source of truth, while <strong>query views</strong> can be rebuilt or optimized as needed.</p>
<h3 id="heading-difference-between-event-sourcing-and-pubsub">Difference Between Event Sourcing and Pub/Sub</h3>
<p>It’s common to confuse Event Sourcing with simple event-driven messaging, but they solve different problems:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Aspect</td><td>Pub/Sub</td><td>Event Sourcing</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Purpose</strong></td><td>Asynchronous communication</td><td>Persistent state representation</td></tr>
<tr>
<td><strong>Event lifetime</strong></td><td>Temporary (in transit)</td><td>Permanent (stored)</td></tr>
<tr>
<td><strong>Consumer type</strong></td><td>Services that react</td><td>Systems that rebuild state</td></tr>
<tr>
<td><strong>Example</strong></td><td>Send email when order created</td><td>Reconstruct order history</td></tr>
</tbody>
</table>
</div><p>You can – and often should – use both together: an event-sourced service emits domain events to notify other systems.</p>
<h3 id="heading-when-to-use-event-sourcing-and-cqrs">When to Use Event Sourcing and CQRS</h3>
<p><strong>Use when:</strong></p>
<ul>
<li><p>You need a <strong>complete audit trail</strong> or historical reconstruction.</p>
</li>
<li><p>The business domain is complex and event-driven by nature (finance, logistics, IoT).</p>
</li>
<li><p>The system requires <strong>high resilience</strong> and state recoverability.</p>
</li>
</ul>
<p><strong>Avoid when:</strong></p>
<ul>
<li><p>You’re building a small, CRUD-oriented app with limited complexity.</p>
</li>
<li><p>You don’t need event replay or full history, as it adds storage and operational overhead.</p>
</li>
<li><p>Your team lacks experience managing distributed consistency and event evolution.</p>
</li>
</ul>
<h3 id="heading-summary-4">Summary</h3>
<p>Event Sourcing and CQRS extend event-driven design to the data layer. Instead of only reacting to events, your system persists them and uses them as the foundation for rebuilding, auditing, and scaling.</p>
<p>This approach transforms your architecture from a static data store into a living timeline, where every change is captured as part of an ongoing story of the system’s behavior.</p>
<p>In the next section, we’ll analyze the benefits and challenges of event-driven architectures. We’ll explore why they scale so effectively, but also why debugging and observability can be tricky in large distributed environments.</p>
<h2 id="heading-8-benefits-and-challenges">8. Benefits and Challenges</h2>
<p>Event-driven architectures offer remarkable scalability, resilience, and flexibility, qualities that make them a cornerstone of modern distributed systems. But these benefits come with trade-offs: debugging becomes more complex, data consistency is harder to guarantee, and operational visibility requires specialized tooling.</p>
<p>In this section, we’ll examine both sides — why EDAs are so powerful and what challenges teams face when implementing them.</p>
<h3 id="heading-benefits-of-eda">Benefits of EDA</h3>
<h4 id="heading-1-scalability-and-responsiveness">1. Scalability and Responsiveness</h4>
<p>Event-driven systems naturally handle high concurrency. Because components react to events asynchronously, they can process workloads in parallel without blocking one another.</p>
<p>For example, in a retail platform:</p>
<ul>
<li><p>The <strong>Order Service</strong> publishes an event.</p>
</li>
<li><p>The <strong>Inventory</strong>, <strong>Billing</strong>, and <strong>Notification</strong> services consume it concurrently.</p>
</li>
</ul>
<p>This decoupling allows systems to scale horizontally, adding new consumers or instances without affecting existing ones.</p>
<p>Also, when combined with brokers like Kafka or RabbitMQ, EDAs can handle massive throughput while maintaining order and reliability.</p>
<h4 id="heading-2-loose-coupling-and-extensibility">2. Loose Coupling and Extensibility</h4>
<p>In a traditional system, integrating new functionality often requires editing existing components. In an event-driven system, new consumers simply subscribe to existing events.</p>
<p>For instance, adding a new Analytics Service that listens for <code>order:created</code> events requires:</p>
<ul>
<li><p>No changes to the Order Service</p>
</li>
<li><p>No disruption to other consumers</p>
</li>
<li><p>No coordination between teams</p>
</li>
</ul>
<p>This makes event-driven systems extensible by design, which is invaluable for large organizations with multiple teams or evolving business logic.</p>
<h4 id="heading-3-resilience-and-fault-isolation">3. Resilience and Fault Isolation</h4>
<p>Since communication is asynchronous, if one service fails, others can continue working. Events are buffered in the broker and delivered later.</p>
<p>This prevents cascading failures typical of tightly coupled, request-response systems. For example, if the Notification Service is down, orders can still be processed, and notifications will be sent once it recovers.</p>
<p>Many brokers also provide durable queues and retries, ensuring no event is lost even under heavy load or downtime.</p>
<h4 id="heading-4-real-time-and-reactive-experiences">4. Real-Time and Reactive Experiences</h4>
<p>Event-driven systems power real-time applications, from chat apps and IoT platforms to fraud detection systems and live analytics dashboards.</p>
<p>Because events represent changes as they happen, they enable instant updates, alerts, and responsive UIs. When combined with technologies like WebSockets, Server-Sent Events, or GraphQL Subscriptions, the same model extends seamlessly to the frontend.</p>
<h4 id="heading-5-auditability-and-traceability">5. Auditability and Traceability</h4>
<p>When paired with Event Sourcing, EDAs provide a complete audit trail of everything that has happened in the system. This is crucial for domains like finance, healthcare, or logistics, where compliance and historical accuracy are mandatory.</p>
<h3 id="heading-challenges-of-eda"><strong>Challenges of EDA</strong></h3>
<h4 id="heading-1-debugging-and-tracing">1. Debugging and Tracing</h4>
<p>Unlike synchronous systems, where a stack trace shows the full call path, event-driven systems are <strong>non-linear</strong>. An event may pass through multiple services, queues, and transformations before triggering an outcome.</p>
<p>This makes it difficult to answer questions like:</p>
<blockquote>
<p>“Why did this event trigger twice?”<br>“Where did this data originate?”<br>“Which services consumed this message?”</p>
</blockquote>
<p>To mitigate this, teams rely on <strong>distributed tracing</strong> tools such as:</p>
<ul>
<li><p>OpenTelemetry</p>
</li>
<li><p>Jaeger</p>
</li>
<li><p>Zipkin</p>
</li>
<li><p>AWS X-Ray</p>
</li>
<li><p>Kafka UI / Conduktor (for message inspection)</p>
</li>
</ul>
<p>Embedding trace IDs in event metadata is a best practice that allows cross-service correlation of events.</p>
<h4 id="heading-2-data-consistency">2. Data Consistency</h4>
<p>Because events are asynchronous, maintaining strict <strong>transactional consistency</strong> is challenging. For example, when an <code>OrderPlaced</code> event triggers multiple actions, those actions may complete at different times – or even fail independently.</p>
<p>To manage this, developers often use:</p>
<ul>
<li><p><strong>Idempotent event handlers</strong> (safe to re-run)</p>
</li>
<li><p><strong>Outbox pattern</strong> (ensuring events are emitted only after successful database commits)</p>
</li>
<li><p><strong>Saga pattern</strong> (for distributed transactions and compensating actions)</p>
</li>
</ul>
<p>These patterns add robustness but also increase system complexity.</p>
<h4 id="heading-3-message-duplication-and-ordering">3. Message Duplication and Ordering</h4>
<p>In distributed systems, you must assume:</p>
<ul>
<li><p>Events may arrive twice (due to retries)</p>
</li>
<li><p>Events may arrive out of order</p>
</li>
</ul>
<p>Because of this, consumers need to be designed for <a target="_blank" href="https://www.freecodecamp.org/news/idempotence-explained/">idempotency</a> and order independence. Many event stores or brokers (like Kafka) provide partitioning and offsets to preserve partial ordering, but global order is rarely guaranteed.</p>
<h4 id="heading-4-operational-complexity">4. Operational Complexity</h4>
<p>While adding a message broker improves decoupling, it also introduces new infrastructure to manage:</p>
<ul>
<li><p>Brokers and topics</p>
</li>
<li><p>Retention policies</p>
</li>
<li><p>Consumer groups</p>
</li>
<li><p>Dead-letter queues (for failed messages)</p>
</li>
</ul>
<p>Monitoring and maintaining these systems requires DevOps expertise and mature observability practices.</p>
<h4 id="heading-5-team-and-mental-model-shift">5. Team and Mental Model Shift</h4>
<p>Event-driven systems require developers to think differently:</p>
<ul>
<li><p>Systems become <strong>reactive</strong>, not procedural.</p>
</li>
<li><p>Data flows are <strong>eventual</strong>, not immediate.</p>
</li>
<li><p>Debugging requires <strong>system-wide visibility</strong>, not local inspection.</p>
</li>
</ul>
<p>For teams used to request-response logic, this transition can be difficult, requiring training, discipline, and careful design reviews.</p>
<h3 id="heading-summary-5">Summary</h3>
<p>Event-driven architectures offer:</p>
<ul>
<li><p>⚙️ Scalability</p>
</li>
<li><p>🧩 Extensibility</p>
</li>
<li><p>🔁 Resilience</p>
</li>
<li><p>⚡ Real-time capabilities</p>
</li>
</ul>
<p>But they demand:</p>
<ul>
<li><p>🧠 Rethinking data flow</p>
</li>
<li><p>🔍 Better observability</p>
</li>
<li><p>🧰 Advanced tooling</p>
</li>
</ul>
<p>When implemented carefully, EDAs unlock new levels of system flexibility and business agility, but success depends on balancing their power with strong governance, well-defined event contracts, and team alignment.</p>
<p>In the next section, we’ll look at <strong>real-world use cases</strong>, examining how leading industries like fintech, e-commerce, and IoT leverage event-driven architectures to achieve scale, responsiveness, and reliability.</p>
<h2 id="heading-9-real-world-use-cases">9. Real-World Use Cases</h2>
<p>Event-driven architectures are not just theoretical patterns. They power many of the systems we use every day. From instant payments to social networks, EDAs provide the backbone for handling real-time data, asynchronous workflows, and massive scalability.</p>
<p>Below are some of the most common and impactful use cases across different industries.</p>
<h3 id="heading-1-financial-and-banking-systems">1. Financial and Banking Systems</h3>
<p>Financial institutions rely heavily on asynchronous, reliable event flows to process millions of operations safely and in real time.</p>
<h4 id="heading-typical-events">Typical Events</h4>
<ul>
<li><p><code>TransactionInitiated</code></p>
</li>
<li><p><code>FundsDeposited</code></p>
</li>
<li><p><code>PaymentProcessed</code></p>
</li>
<li><p><code>FraudAlertTriggered</code></p>
</li>
</ul>
<h4 id="heading-how-it-works">How It Works</h4>
<p>When a user initiates a payment:</p>
<ol>
<li><p>The Payment Service emits a <code>PaymentInitiated</code> event.</p>
</li>
<li><p>The Fraud Detection Service subscribes to it, analyzing risk in parallel.</p>
</li>
<li><p>The Ledger Service records the transaction asynchronously.</p>
</li>
<li><p>The Notification Service sends confirmations.</p>
</li>
</ol>
<p>Each component operates independently, and failures or slow responses in one don’t block others.</p>
<h4 id="heading-benefits">Benefits</h4>
<ul>
<li><p>Real-time fraud detection</p>
</li>
<li><p>Parallel transaction processing</p>
</li>
<li><p>Clear audit trail for compliance (with Event Sourcing)</p>
</li>
</ul>
<p><strong>Example:</strong> Modern payment systems (like Revolut, Stripe, and PayPal) use event-driven microservices to orchestrate transactions securely and at scale.</p>
<h3 id="heading-2-e-commerce-platforms">2. E-commerce Platforms</h3>
<p>E-commerce systems are naturally event-driven. Every customer action generates events that ripple across subsystems.</p>
<h4 id="heading-typical-events-1">Typical Events</h4>
<ul>
<li><p><code>OrderCreated</code></p>
</li>
<li><p><code>ItemAddedToCart</code></p>
</li>
<li><p><code>InventoryUpdated</code></p>
</li>
<li><p><code>ShipmentDispatched</code></p>
</li>
</ul>
<h4 id="heading-event-flow-example">Event Flow Example</h4>
<p>When a user places an order:</p>
<ol>
<li><p>The Order Service emits <code>OrderCreated</code>.</p>
</li>
<li><p>Inventory Service reserves stock.</p>
</li>
<li><p>Billing Service processes the payment.</p>
</li>
<li><p>Shipping Service schedules delivery.</p>
</li>
<li><p>Analytics Service records metrics.</p>
</li>
</ol>
<p>Each step occurs asynchronously, allowing thousands of orders to be processed concurrently.</p>
<h4 id="heading-benefits-1">Benefits</h4>
<ul>
<li><p>High scalability during peak sales (for example, Black Friday)</p>
</li>
<li><p>Fault isolation between modules</p>
</li>
<li><p>Easy integration of new services (for example, loyalty or recommendation engines)</p>
</li>
</ul>
<p><strong>Example:</strong> Amazon and Shopify both use event-based pipelines for order management, tracking, and analytics.</p>
<h3 id="heading-3-iot-and-sensor-networks">3. IoT and Sensor Networks</h3>
<p>In IoT ecosystems, thousands or millions of devices constantly emit data. Event-driven architectures are essential for ingesting, processing, and reacting to these streams efficiently.</p>
<h4 id="heading-typical-events-2">Typical Events</h4>
<ul>
<li><p><code>TemperatureMeasured</code></p>
</li>
<li><p><code>DeviceConnected</code></p>
</li>
<li><p><code>MotionDetected</code></p>
</li>
<li><p><code>BatteryLow</code></p>
</li>
</ul>
<h4 id="heading-event-flow-example-1">Event Flow Example</h4>
<ol>
<li><p>Devices publish sensor data to a message broker (like MQTT, Kafka, or AWS IoT Core).</p>
</li>
<li><p>The Processing Service filters and enriches data.</p>
</li>
<li><p>Alert Services emit notifications if thresholds are crossed.</p>
</li>
<li><p>Analytics Pipelines store aggregated data for insights.</p>
</li>
</ol>
<h4 id="heading-benefits-2">Benefits</h4>
<ul>
<li><p>Real-time monitoring</p>
</li>
<li><p>Predictive maintenance (based on event patterns)</p>
</li>
<li><p>Scalable ingestion from thousands of sources</p>
</li>
</ul>
<p><strong>Example:</strong> Smart cities and connected vehicles use event-driven systems to react to sensor data in milliseconds, adjusting traffic lights, tracking fleets, or monitoring energy grids.</p>
<h3 id="heading-4-real-time-analytics-and-monitoring">4. Real-Time Analytics and Monitoring</h3>
<p>Modern analytics systems depend on <strong>stream processing</strong>, continuously ingesting and analyzing events to derive insights instantly.</p>
<h4 id="heading-typical-events-3">Typical Events</h4>
<ul>
<li><p><code>PageViewed</code></p>
</li>
<li><p><code>UserLoggedIn</code></p>
</li>
<li><p><code>MetricUpdated</code></p>
</li>
</ul>
<h4 id="heading-event-flow-example-2">Event Flow Example</h4>
<ol>
<li><p>Applications emit user interaction events to a message queue.</p>
</li>
<li><p>A Stream Processor (like Apache Flink or Kafka Streams) aggregates events in real time.</p>
</li>
<li><p>Dashboards and alerting systems consume processed results via WebSockets or APIs.</p>
</li>
</ol>
<h4 id="heading-benefits-3">Benefits</h4>
<ul>
<li><p>Live metrics and dashboards</p>
</li>
<li><p>Early anomaly detection</p>
</li>
<li><p>Continuous feedback loops for ML models</p>
</li>
</ul>
<p><strong>Example:</strong> Netflix uses event-driven data pipelines (built on Kafka) to monitor playback quality and deliver adaptive streaming experiences in real time.</p>
<h3 id="heading-5-social-networks-and-messaging-apps">5. Social Networks and Messaging Apps</h3>
<p>Social platforms are fundamentally <strong>event-driven systems</strong>. Every post, like, message, or comment is an event that triggers updates across multiple systems.</p>
<h4 id="heading-typical-events-4">Typical Events</h4>
<ul>
<li><p><code>PostCreated</code></p>
</li>
<li><p><code>MessageSent</code></p>
</li>
<li><p><code>UserMentioned</code></p>
</li>
<li><p><code>NotificationDelivered</code></p>
</li>
</ul>
<h4 id="heading-event-flow-example-3">Event Flow Example</h4>
<p>When a user sends a message:</p>
<ol>
<li><p>The Chat Service emits <code>MessageSent</code>.</p>
</li>
<li><p>The Notification Service alerts the recipient.</p>
</li>
<li><p>The Search Index Service updates conversations.</p>
</li>
<li><p>The Analytics Service logs engagement metrics.</p>
</li>
</ol>
<h4 id="heading-benefits-4">Benefits</h4>
<ul>
<li><p>Instant notifications and updates</p>
</li>
<li><p>Asynchronous scalability across millions of users</p>
</li>
<li><p>Modular and evolvable product features</p>
</li>
</ul>
<p><strong>Example:</strong> Slack, WhatsApp, and Facebook Messenger rely on distributed event buses to coordinate billions of message and presence events per day.</p>
<h3 id="heading-6-workflow-automation-and-orchestration">6. Workflow Automation and Orchestration</h3>
<p>Workflow systems such as document approvals, CI/CD pipelines, or business processes are often built around events.</p>
<h4 id="heading-typical-events-5">Typical Events</h4>
<ul>
<li><p><code>TaskCreated</code></p>
</li>
<li><p><code>TaskCompleted</code></p>
</li>
<li><p><code>ApprovalGranted</code></p>
</li>
<li><p><code>PipelineDeployed</code></p>
</li>
</ul>
<h4 id="heading-how-it-works-1">How It Works</h4>
<p>Each action in a workflow triggers the next step through events, allowing flexible orchestration without hardcoding dependencies. This makes it easy to reconfigure or extend workflows dynamically.</p>
<p><strong>Example:</strong> GitHub Actions and Zapier use event-driven models to execute workflows automatically based on triggers (for example, a commit, file upload, or webhook).</p>
<h3 id="heading-summary-6">Summary</h3>
<p>Event-driven architectures power some of the most demanding digital systems in existence. Across industries, they provide:</p>
<ul>
<li><p>⚙️ <strong>Scalable infrastructure</strong> for handling massive event streams</p>
</li>
<li><p>⏱ <strong>Real-time responsiveness</strong> to user and system actions</p>
</li>
<li><p>🧩 <strong>Modularity and evolution</strong> as systems grow by subscribing to new events</p>
</li>
</ul>
<p>Whether in fintech, IoT, e-commerce, or analytics, EDAs have proven to be a flexible, future-proof foundation for building systems that react intelligently to change.</p>
<p>In the final section, we’ll synthesize the lessons learned, summarizing best practices, common pitfalls, and key takeaways for adopting event-driven architectures successfully in modern JavaScript ecosystems.</p>
<h2 id="heading-10-best-practices-and-conclusions">10. Best Practices and Conclusions</h2>
<p>Event-driven architectures offer a flexible, scalable, and future-proof foundation for modern software systems. But their power comes with complexity: events are easy to emit but hard to manage at scale without discipline and consistency.</p>
<p>This final section distills practical best practices for designing and operating event-driven systems effectively, followed by a summary reflection on when and how to adopt this architecture.</p>
<h3 id="heading-1-version-and-validate-events">1. Version and Validate Events</h3>
<p>Events evolve over time as your system grows. Adding or changing fields can break consumers if versions aren’t managed carefully.</p>
<p><strong>Best practices:</strong></p>
<ul>
<li><p>Use explicit versioning in event names or schemas (for example, <code>order:created.v2</code>).</p>
</li>
<li><p>Validate event payloads using JSON Schema or tools like <code>ajv</code> or <code>Zod</code>.</p>
</li>
<li><p>Maintain a central event catalog or schema registry shared by all services.</p>
</li>
</ul>
<p>This ensures backward compatibility and reduces surprises when consumers update at different times.</p>
<h3 id="heading-2-design-for-idempotency">2. Design for Idempotency</h3>
<p>In distributed systems, <strong>duplicate messages</strong> are inevitable – retries, network hiccups, or failovers can cause events to be processed multiple times.</p>
<p>Make consumers idempotent, meaning they can handle the same event repeatedly without unintended side effects.</p>
<p>For example:</p>
<pre><code class="lang-typescript"><span class="hljs-keyword">if</span> (!processedEvents.has(event.id)) {
  process(event);
  processedEvents.add(event.id);
}
</code></pre>
<p>Always include a unique event ID and check for duplicates before applying changes.</p>
<h3 id="heading-3-keep-events-meaningful-and-self-contained">3. Keep Events Meaningful and Self-Contained</h3>
<p>Each event should represent a <strong>domain-level change</strong>, not just a technical signal. Avoid overly generic messages like <code>"update"</code> or <code>"dataChanged"</code>, as they make debugging and evolution difficult.</p>
<p>Good events:</p>
<ul>
<li><p>Describe <strong>what happened</strong> (not what to do).</p>
</li>
<li><p>Include <strong>enough context</strong> for consumers to act independently.</p>
</li>
<li><p>Avoid exposing internal database models directly.</p>
</li>
</ul>
<p>Example:</p>
<pre><code class="lang-typescript">{
  <span class="hljs-string">"event"</span>: <span class="hljs-string">"user:email:updated"</span>,
  <span class="hljs-string">"data"</span>: { <span class="hljs-string">"userId"</span>: <span class="hljs-number">123</span>, <span class="hljs-string">"oldEmail"</span>: <span class="hljs-string">"a@x.com"</span>, <span class="hljs-string">"newEmail"</span>: <span class="hljs-string">"b@x.com"</span> }
}
</code></pre>
<p>This provides clear, business-oriented semantics.</p>
<h3 id="heading-4-implement-robust-error-handling-and-dead-letter-queues">4. Implement Robust Error Handling and Dead-Letter Queues</h3>
<p>Not every event will be processed successfully. Network failures, schema mismatches, or transient service outages are inevitable.</p>
<p><strong>Mitigation strategies:</strong></p>
<ul>
<li><p>Use <strong>retry policies</strong> with exponential backoff.</p>
</li>
<li><p>Send failed messages to a <strong>dead-letter queue (DLQ)</strong> for inspection.</p>
</li>
<li><p>Build <strong>alerting and monitoring</strong> on DLQ metrics to detect recurring issues.</p>
</li>
</ul>
<p>This ensures resilience and prevents message loss.</p>
<h3 id="heading-5-ensure-observability-and-traceability">5. Ensure Observability and Traceability</h3>
<p>Debugging asynchronous flows requires visibility. Embed tracing and correlation data into your events:</p>
<pre><code class="lang-typescript">{
  <span class="hljs-string">"event"</span>: <span class="hljs-string">"payment:processed"</span>,
  <span class="hljs-string">"eventId"</span>: <span class="hljs-string">"9b7f...c0"</span>,
  <span class="hljs-string">"traceId"</span>: <span class="hljs-string">"c74d...d9"</span>,
  <span class="hljs-string">"timestamp"</span>: <span class="hljs-string">"2025-11-03T13:45:00Z"</span>
}
</code></pre>
<p>Integrate with tools like:</p>
<ul>
<li><p>OpenTelemetry for distributed tracing</p>
</li>
<li><p>Jaeger or Zipkin for visualization</p>
</li>
<li><p>Kafka UI, Redpanda Console, or Conduktor for message inspection</p>
</li>
</ul>
<p>This allows you to reconstruct event lifecycles across services, which is critical for debugging, compliance, and performance tuning.</p>
<h3 id="heading-6-use-patterns-for-reliability">6. Use Patterns for Reliability</h3>
<p>Certain design patterns make large-scale event-driven systems more reliable:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Pattern</td><td>Purpose</td></tr>
</thead>
<tbody>
<tr>
<td><strong>Outbox Pattern</strong></td><td>Ensures events are emitted only after DB transactions succeed</td></tr>
<tr>
<td><strong>Saga Pattern</strong></td><td>Coordinates distributed transactions with compensating actions</td></tr>
<tr>
<td><strong>Event Choreography</strong></td><td>Lets services react naturally without central orchestration</td></tr>
<tr>
<td><strong>Event Carried State Transfer</strong></td><td>Includes enough data in events for consumers to act independently</td></tr>
</tbody>
</table>
</div><p>Applying these patterns reduces race conditions and improves data consistency.</p>
<h3 id="heading-7-choose-the-right-broker-for-the-job">7. Choose the Right Broker for the Job</h3>
<p>Different brokers serve different use cases:</p>
<div class="hn-table">
<table>
<thead>
<tr>
<td>Broker</td><td>Strength</td></tr>
</thead>
<tbody>
<tr>
<td><strong>RabbitMQ</strong></td><td>Simple, reliable queues; easy to use for small systems</td></tr>
<tr>
<td><strong>Kafka</strong></td><td>High throughput, event persistence, replayability</td></tr>
<tr>
<td><strong>Redis Streams</strong></td><td>Lightweight, in-memory stream processing</td></tr>
<tr>
<td><strong>NATS / Pulsar</strong></td><td>Low-latency, cloud-native messaging for microservices</td></tr>
</tbody>
</table>
</div><p>Your choice depends on throughput, durability, and delivery guarantees.</p>
<h3 id="heading-8-balance-event-driven-and-request-driven-approaches">8. Balance Event-Driven and Request-Driven Approaches</h3>
<p>Event-driven systems excel in asynchronous workflows, but not everything should be event-driven.</p>
<p>Use <strong>synchronous APIs</strong> for immediate, transactional actions (for example, authentication, user profile lookup). And use <strong>events</strong> for background or decoupled processes (for example, analytics, notifications, async updates).</p>
<p>Combining both models yields the best balance of responsiveness and reliability.</p>
<h3 id="heading-9-educate-and-align-the-team">9. Educate and Align the Team</h3>
<p>Architecture is as much about people as it is about technology. Ensure developers share a common understanding of event naming conventions, schema versioning policies, error handling and retry rules, and ownership of producer and consumer responsibilities.</p>
<p>Without alignment, even the best tools lead to inconsistent, brittle systems.</p>
<h3 id="heading-10-start-small-then-evolve">10. Start Small, Then Evolve</h3>
<p>You don’t need Kafka clusters or event sourcing to begin. Start small:</p>
<ul>
<li><p>Use Node.js <code>EventEmitter</code> or a simple in-memory bus for decoupling modules.</p>
</li>
<li><p>Gradually evolve toward distributed brokers as complexity increases.</p>
</li>
</ul>
<p>The key is incremental adoption – building understanding before scaling infrastructure.</p>
<h2 id="heading-conclusion"><strong>Conclusion</strong></h2>
<p>Event-driven architectures fundamentally change how we design software. By focusing on what happens rather than what to do next, systems become more adaptable, reactive, and aligned with real-world processes.</p>
<p>In JavaScript – a language born from events – this paradigm feels especially natural. From browser interactions to Node.js microservices, event-driven thinking unifies the frontend and backend under a single principle: <strong>react to change</strong>.</p>
<p>When used wisely, EDA is not just a design pattern – it’s an architectural mindset that empowers systems to evolve continuously, communicate fluidly, and stay resilient in the face of complexity.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Handle Events in React – Explained with Code Examples ]]>
                </title>
                <description>
                    <![CDATA[ Event handling is fundamental to understanding how React processes browser events and updates the DOM. As a React developer, it's a critical skill to have, as it enables efficient management of user interactions within web apps.   This article covers... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-to-handle-events-in-react-19/</link>
                <guid isPermaLink="false">66bc4d0b82b2326c16c01a5d</guid>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Matéu.sh ]]>
                </dc:creator>
                <pubDate>Mon, 13 May 2024 09:26:31 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/05/React-logo.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Event handling is fundamental to understanding how React processes browser events and updates the DOM. As a React developer, it's a critical skill to have, as it enables efficient management of user interactions within web apps.  </p>
<p>This article covers how to set up event handlers and proceeds to more elegant techniques for event management. You'll learn how to create events in React components, pass arguments to the handlers, and prevent default behaviors.  </p>
<p>We'll also cover common event handling patterns and best practices to ensure your applications are performant and easy to maintain.</p>
<h2 id="heading-basic-principles-of-event-handling-in-react">Basic Principles of Event Handling in React</h2>
<p>Event handling in React is guided by a few basic principles that align with its component-based architecture. These principles include:</p>
<ul>
<li>Synthetic event system</li>
<li>Naming conventions</li>
<li>Passing event handlers as props</li>
<li>Inline function and component methods</li>
</ul>
<p>React uses a synthetic event system that ensures events behave consistently across different browsers. This wraps the native event system in browsers, providing a unified API regardless of the browser in which React is run.</p>
<p>Naming conventions revolve around a set of consistent naming that developers use for identifying events and the handler functions at a glance. Every event uses a <code>camelCase</code> naming convention, and the handler function they run is prefixed with "handle", followed by the event name. For example, an <code>onClick</code> event running a <code>handleClick</code> function.</p>
<p>Event handlers are the functions that run when the event is fired. They're usually defined before the render, just above the return statement. On many occasions, they are also passed as <code>props</code> to components. This aligns with React component-based architecture, allowing event logic to be embedded within the components using them.</p>
<p>In React components, events typically run inline functions or standalone functions within the component when fired. With this, you can utilize hooks like <code>useState</code> for state and <code>useCallback</code> for memoizing handler functions. This helps manage state changes and optimize performance.</p>
<h2 id="heading-how-to-create-event-handlers-in-react-components">How to Create Event Handlers in React Components</h2>
<p>Creating an event in React starts with attaching the event name to the element that will fire it, with the handler function referenced in it:</p>
<pre><code class="lang-jsx">&lt;button onClick={handleClick}&gt;
  Click me
&lt;/button&gt;
</code></pre>
<p>What follows is to define that handler function, because it's the function that will run when the event is triggered:</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
   alert(<span class="hljs-string">'You clicked me'</span>);
};
</code></pre>
<p>This is the full code that has been imported into the <code>page.jsx</code> file of a Next.js starter:</p>
<pre><code class="lang-jsx"><span class="hljs-string">'use client'</span>;

<span class="hljs-keyword">const</span> Counter = <span class="hljs-function">() =&gt;</span> {
 <span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">() =&gt;</span> {
   alert(<span class="hljs-string">'You clicked me!'</span>);
 };

 <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"p-10 flex items-center"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
       <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>
       <span class="hljs-attr">className</span>=<span class="hljs-string">"bg-green-400 px-4 py-2 rounded mx-auto"</span>
     &gt;</span>
       Click me
     <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
 );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p>And here's what shows in the browser when the button is clicked:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/onclick-event.png" alt="Image" width="600" height="400" loading="lazy">
<em>Next.js application displaying alert window</em></p>
<p>You can also trigger the event without a separate function. You can do this by defining the function to run as an anonymous function inside the event:</p>
<pre><code class="lang-jsx">&lt;button onClick={<span class="hljs-function">() =&gt;</span> alert(<span class="hljs-string">'You clicked me!'</span>)}&gt;
  Click me
&lt;/button&gt;
</code></pre>
<p>If you want to update the component state based on an event, you might need the <code>useState</code> hook. Here's an example that shows that using a simple counter application:</p>
<pre><code class="lang-jsx"><span class="hljs-string">'use client'</span>;

<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> Counter = <span class="hljs-function">() =&gt;</span> {
 <span class="hljs-keyword">const</span> [count, setCount] = useState(<span class="hljs-number">0</span>);

 <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"flex items-center justify-center space-x-8 p-10"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
       <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count - 1)}
       className="bg-red-500 hover:bg-red-600 text-white font-bold px-4 py-2 rounded "
     &gt;
       Decrement
     <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-4xl font-semibold text-gray-800"</span>&gt;</span>{count}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
       <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> setCount(count + 1)}
       className="bg-green-500 hover:bg-green-600 text-white font-bold px-4 py-2 rounded "
     &gt;
       Increment
     <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
 );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> Counter;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/counter-app.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Counter App in Next.js (Animated GIF)</em></p>
<p><code>onChange</code> and <code>onSubmt</code> are other popular events in React. <code>onChange</code> is used on <code>input</code> elements and <code>onSubmit</code> is used on a <code>form</code> element.</p>
<p>Here's an example of an <code>onChange</code> event:</p>
<pre><code class="lang-jsx"><span class="hljs-string">'use client'</span>;

<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> MyInput = <span class="hljs-function">() =&gt;</span> {
 <span class="hljs-keyword">const</span> [inputValue, setInputValue] = useState(<span class="hljs-string">''</span>);

 <span class="hljs-keyword">const</span> handleChange = <span class="hljs-function">(<span class="hljs-params">e</span>) =&gt;</span> {
   setInputValue(e.target.value);
 };

 <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
       <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
       <span class="hljs-attr">value</span>=<span class="hljs-string">{inputValue}</span>
       <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleChange}</span>
       <span class="hljs-attr">className</span>=<span class="hljs-string">"border border-green-400 p-2 rounded shadow"</span>
       <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Type something..."</span>
     /&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"mt-4 text-green-400"</span>&gt;</span>You typed: {inputValue}<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
 );
};

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> MyInput;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/onchange-event.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Handling input changes in React</em></p>
<p>We'll look at an example of an <code>onSubmit</code> event in the section on how to prevent the default browser behavior when submitting a form.</p>
<p>Other examples of events include keyboard events like <code>onKeyDown</code>, <code>onKeyPress</code>, and <code>onKeyUp</code>,  mouse events like <code>onMouseUp</code>,  <code>onMouseDown</code>, <code>onMouseEnter</code> <code>onDrag</code>, and more. Any popular event in JavaScript is available in React. The only difference is that events are written in <code>camelCase</code> in React.</p>
<h2 id="heading-how-to-pass-arguments-to-event-handlers">How to Pass Arguments to Event Handlers</h2>
<p>Passing arguments to event handlers in React is a common requirement when you need to perform actions on specific data associated with an event. For example, deleting or editing a resource.</p>
<p>To do this, the handler function needs to take in a parameter:</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> handleClick = <span class="hljs-function">(<span class="hljs-params">item</span>) =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button click for:'</span>, item);
 };
</code></pre>
<p>You then pass an argument corresponding to that parameter into the anonymous function of the event:</p>
<pre><code class="lang-jsx">&lt;button onClick={<span class="hljs-function">() =&gt;</span> handleClick(item)}&gt;Click Me&lt;/button&gt;
</code></pre>
<p>Here's an example handling task deletion in a <code>TaskManager</code> component:</p>
<pre><code class="lang-jsx"><span class="hljs-string">'use client'</span>;

<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-keyword">const</span> TaskManager = <span class="hljs-function">() =&gt;</span> {
 <span class="hljs-keyword">const</span> [tasks, setTasks] = useState([
   { <span class="hljs-attr">id</span>: <span class="hljs-number">1</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">'Read an article'</span> },
   { <span class="hljs-attr">id</span>: <span class="hljs-number">2</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">'Read a book'</span> },
   { <span class="hljs-attr">id</span>: <span class="hljs-number">3</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">'Write an article'</span> },
   { <span class="hljs-attr">id</span>: <span class="hljs-number">4</span>, <span class="hljs-attr">text</span>: <span class="hljs-string">'Code'</span> },
 ]);

 <span class="hljs-comment">// Function takes a a taskId parameter</span>
 <span class="hljs-keyword">const</span> deleteTask = <span class="hljs-function">(<span class="hljs-params">taskId</span>) =&gt;</span> {
   setTasks(<span class="hljs-function">(<span class="hljs-params">currentTasks</span>) =&gt;</span>
     currentTasks.filter(<span class="hljs-function">(<span class="hljs-params">task</span>) =&gt;</span> task.id !== taskId)
   );
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Deleted task with ID:'</span>, taskId);
 };

 <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"p-5 max-w-md mx-auto bg-gray-100 rounded-lg shadow"</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"list-none space-y-2"</span>&gt;</span>
       {tasks.map((task) =&gt; (
         <span class="hljs-tag">&lt;<span class="hljs-name">li</span>
           <span class="hljs-attr">key</span>=<span class="hljs-string">{task.id}</span>
           <span class="hljs-attr">className</span>=<span class="hljs-string">"flex justify-between items-center bg-white p-3 rounded shadow-sm"</span>
         &gt;</span>
           {task.text}
           <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
             // <span class="hljs-attr">onClick</span> <span class="hljs-attr">event</span> <span class="hljs-attr">takes</span> <span class="hljs-attr">a</span> <span class="hljs-attr">task.id</span> <span class="hljs-attr">argument</span> <span class="hljs-attr">to</span> <span class="hljs-attr">account</span> <span class="hljs-attr">for</span> <span class="hljs-attr">the</span> <span class="hljs-attr">taskId</span> <span class="hljs-attr">parameter</span> <span class="hljs-attr">of</span> <span class="hljs-attr">the</span> <span class="hljs-attr">function</span>
             <span class="hljs-attr">onClick</span>=<span class="hljs-string">{()</span> =&gt;</span> deleteTask(task.id)}
             className="bg-red-500 hover:bg-red-700 text-white font-bold py-1 px-3 rounded"
           &gt;
             Delete
           <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
         <span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
       ))}
     <span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
 );
};


<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> TaskManager;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/task-deletion.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Item delete is a great example of parametrized event handler</em></p>
<h2 id="heading-common-event-handling-patterns-in-react">Common Event Handling Patterns in React</h2>
<p>Event handling patterns refer to the techniques for handling user interactions within React components.</p>
<p>These patterns include but aren't limited to:</p>
<ul>
<li>Binding event handlers with <code>useCallback</code> to memoize the handler</li>
<li>Event handlers with parameters (you've seen this in the section on how to pass arguments to event handlers)</li>
<li>Conditional event handling</li>
<li>Event delegation</li>
<li>Event bubbling</li>
<li>Optimized handling for lists</li>
<li>Inline arrow functions (anonymous functions that you pass into event handlers)</li>
</ul>
<p>Here's an example using <code>useCallback</code> to prevent creating a new function on every render:</p>
<pre><code class="lang-jsx"><span class="hljs-string">'use client'</span>;

<span class="hljs-keyword">import</span> { useCallback } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">HandlerComponent</span>(<span class="hljs-params"></span>) </span>{
 <span class="hljs-keyword">const</span> handleClick = useCallback(<span class="hljs-function">() =&gt;</span> {
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Button clicked'</span>);
 }, []);

 <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleClick}</span>&gt;</span>
     Click Me
   <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
 );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> HandlerComponent;
</code></pre>
<p>And here's an example of conditional event handling:</p>
<pre><code class="lang-jsx"><span class="hljs-string">'use client'</span>;

<span class="hljs-keyword">import</span> { useState } <span class="hljs-keyword">from</span> <span class="hljs-string">'react'</span>;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">CheckLogin</span>(<span class="hljs-params"></span>) </span>{
 <span class="hljs-keyword">const</span> [isLoggedIn, setLoggedIn] = useState(<span class="hljs-literal">false</span>);

 <span class="hljs-keyword">const</span> toggleLogin = <span class="hljs-function">() =&gt;</span> {
   setLoggedIn(!isLoggedIn);
 };

 <span class="hljs-keyword">const</span> handleLogin = <span class="hljs-function">() =&gt;</span> {
   <span class="hljs-keyword">if</span> (isLoggedIn) {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User is logged in'</span>);
   } <span class="hljs-keyword">else</span> {
     <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'User is logged out'</span>);
   }
 };

 <span class="hljs-keyword">return</span> (
   <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">div</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">h2</span> <span class="hljs-attr">className</span>=<span class="hljs-string">"text-3xl text-center mb-4"</span>&gt;</span>
       {isLoggedIn ? 'User is logged in' : 'User is not logged in'}
     <span class="hljs-tag">&lt;/<span class="hljs-name">h2</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
       <span class="hljs-attr">onClick</span>=<span class="hljs-string">{handleLogin}</span>
       <span class="hljs-attr">className</span>=<span class="hljs-string">"bg-green-400 hover:bg-green-500 px-2 py-3 rounded mr-3"</span>
     &gt;</span>
       Check Login
     <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
     <span class="hljs-tag">&lt;<span class="hljs-name">button</span>
       <span class="hljs-attr">onClick</span>=<span class="hljs-string">{toggleLogin}</span>
       <span class="hljs-attr">className</span>=<span class="hljs-string">"bg-green-400 hover:bg-green-500 px-2 py-3 rounded"</span>
     &gt;</span>
       {isLoggedIn ? 'Log Out' : 'Log In'}
     <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span></span>
 );
}

<span class="hljs-keyword">export</span> <span class="hljs-keyword">default</span> CheckLogin;
</code></pre>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/05/conditional-event.gif" alt="Image" width="600" height="400" loading="lazy">
<em>Next.js app checks if user is logged-in</em></p>
<h2 id="heading-how-to-prevent-the-default-browser-behavior-in-event-handlers">How to Prevent the Default Browser Behavior in Event Handlers</h2>
<p>Default browser behavior is the automatic actions the browser performs when a specific event is fired. In event handling, the most common default browser behavior is that it refreshes when a form is submitted. </p>
<p>To prevent the browser from refreshing when a form is submitted, or prevent any other default behavior, pass the <code>event</code> parameter into the function handling the <code>onSubmit</code> event, then use that <code>event</code> to call a <code>preventDefault</code> function.</p>
<pre><code class="lang-jsx"><span class="hljs-keyword">const</span> handleSubmit = <span class="hljs-function">(<span class="hljs-params">event</span>) =&gt;</span> {
 <span class="hljs-comment">// prevent the default behavior</span>
 event.preventDefault();
};

<span class="hljs-keyword">return</span> (
 <span class="hljs-comment">// reference the function in onSubmit</span>
 <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onSubmit</span>=<span class="hljs-string">{handleSubmit}</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">input</span>
     <span class="hljs-attr">type</span>=<span class="hljs-string">"text"</span>
     <span class="hljs-attr">value</span>=<span class="hljs-string">{inputValue}</span>
     <span class="hljs-attr">onChange</span>=<span class="hljs-string">{handleInputChange}</span>
     <span class="hljs-attr">placeholder</span>=<span class="hljs-string">"Enter something..."</span>
   /&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"submit"</span>&gt;</span>Submit<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
 <span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span></span>
);
</code></pre>
<h2 id="heading-best-practices-for-efficient-event-handling-in-react">Best Practices for Efficient Event Handling in React</h2>
<p>Here are the most important rules for event handling in React:</p>
<h3 id="heading-avoid-using-anonymous-arrow-functions-inside-events">Avoid Using Anonymous Arrow Functions Inside Events</h3>
<p>It looks convenient to use arrow functions directly in events, like <code>onClick={() =&gt; console.log('button clicked')})</code>. The downside to this is that it can lead to performance issues because a new function is created on every render.</p>
<p>Always define the handler function to run when the event is fired outside the render method to avoid those performance issues.</p>
<h3 id="heading-memoize-events-with-usecallback-hook">Memoize Events with useCallback hook</h3>
<p>For components that re-render often, memoizing the handlers in it with the <code>useCallback</code> hook can prevent unnecessary re-renders. This is useful when passing events as props to child components that might re-render unnecessarily.</p>
<h3 id="heading-use-event-delegation">Use Event Delegation</h3>
<p>For multiple similar elements, like items in a list, consider using event delegation. Attach a single event listener to the parent element and use the event target to handle user interaction with child elements. This reduces the number of event listeners and can improve performance.</p>
<h3 id="heading-prevent-default-behavior-where-necessary">Prevent Default Behavior Where Necessary</h3>
<p>Use <code>event.preventDefault()</code> in your event handlers when you need to stop the browser from performing default actions, like submitting a form. However, you should use this method prudently to avoid blocking browser behaviors unnecessarily.</p>
<h3 id="heading-clean-up-event-listeners">Clean Up Event Listeners</h3>
<p>If you set up your event listeners in <code>useEffect</code>, always return a cleanup function to remove the event listener. Otherwise, it'll cause memory leaks.</p>
<h3 id="heading-test-event-handlers">Test Event Handlers</h3>
<p>Make sure your event handlers are covered in your unit and integration tests. Testing frameworks like Jest combined with React Testing Library can help verify that your event handlers are functioning as expected.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article, you learned the fundamentals of event handling in React, focusing on how to use the React synthetic event system to create events in React web apps.</p>
<p>We explored defining event handlers, passing arguments, and preventing default browser behaviors to enhance user experiences.</p>
<p>In addition, you learned about the benefits of using <code>useCallback</code> to optimize event handlers for efficient performance under various user interactions.</p>
<p>With these insights, you should be able to implement event handling in your projects, so you can improve both functionality and user engagement.</p>
<h2 id="heading-bring-your-react-skills-to-the-next-level">Bring your React skills to the next level</h2>
<p>Would you like to learn more about event handling or other React concepts? Then join my React course on Udemy. I will show you how to become a better React developer by building a 2048 Game. Building games make learning more fun and enjoyable.</p>
<p><a target="_blank" href="https://assets.mateu.sh/r/fcc-events-in-react"><img src="https://assets.mateu.sh/assets/fcc-events-in-react" alt="Next.js crash course on Udemy" width="600" height="400" loading="lazy"></a></p>
<p> So join now and start your journey to mastering React!</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript in the Browser – How the Document Object Model (DOM) and Events Work ]]>
                </title>
                <description>
                    <![CDATA[ In this in-depth tutorial, you'll learn all about the Document Object Model, or DOM for short. As a web developer, understanding the DOM is fundamental for interacting with web browsers and creating dynamic web applications.  Throughout this guide, w... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-in-the-browser-dom-and-events/</link>
                <guid isPermaLink="false">66c7218887ceefbdaf9b921b</guid>
                
                    <category>
                        <![CDATA[ browser ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Document Object Model ]]>
                    </category>
                
                    <category>
                        <![CDATA[ DOM ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ handbook ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Samyak Jain ]]>
                </dc:creator>
                <pubDate>Thu, 15 Feb 2024 20:07:14 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2024/02/JavaScript-in-the-Browser-with-Photo-Cover.png" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>In this in-depth tutorial, you'll learn all about the Document Object Model, or DOM for short. As a web developer, understanding the DOM is fundamental for interacting with web browsers and creating dynamic web applications. </p>
<p>Throughout this guide, we will explore the DOM's hierarchical tree structure, essential properties, and methods for accessing and modifying nodes. We'll also dive into event handling and various techniques for efficient DOM manipulation.</p>
<p>By the end of this guide, you should be able to confidently manipulate the DOM to meet the demands of your web development projects.</p>
<h3 id="heading-prerequisites">Prerequisites:</h3>
<p>While this guide is designed to be beginner-friendly and accessible to anyone, having a basic understanding of JavaScript fundamentals will greatly enhance your ability to grasp the practical concepts covered. </p>
<p>Also, familiarity with HTML and CSS is a plus and will help you comprehend and apply the material we cover. </p>
<p>If you're new to JavaScript, consider familiarizing yourself with variables, data types, functions, loops, and basic DOM manipulation techniques before diving into this tutorial. This foundational knowledge will ensure a smoother learning experience as we explore more advanced topics related to the Document Object Model (DOM).</p>
<h2 id="heading-table-of-contents">Table of Contents</h2>
<ol>
<li><a class="post-section-overview" href="#browser-object-model-bom-">What is the Browser Object Model (BOM)</a>?</li>
<li><a class="post-section-overview" href="#what-is-the-document-object-model-dom">What is the Document Object Model (DOM)?</a></li>
<li><a class="post-section-overview" href="#heading-dom-tree-structure">DOM Tree Structure</a><br>– <a class="post-section-overview" href="#heading-types-of-nodes-in-the-dom-tree">Types of Nodes in the DOM Tree</a><br>– <a class="post-section-overview" href="#heading-node-relationships">Node Relationships</a></li>
<li><a class="post-section-overview" href="#heading-how-to-work-with-dom-elements">How to Work with DOM Elements</a><br>– <a class="post-section-overview" href="#methods-for-traversing-the-dom-">Traversing the DOM</a><br>– <a class="post-section-overview" href="#heading-methods-for-querying-dom-elements">Methods for Querying DOM Elements</a><br>– <a class="post-section-overview" href="#heading-matches-closest-and-contains">Specialized Selectors (Matches, Closest, Contains)</a><br>– <a class="post-section-overview" href="#heading-how-to-inspect-dom-elements">How to Inspect DOM Elements</a><br>– <a class="post-section-overview" href="#heading-table-navigation-in-the-dom">Table Navigation in the DOM</a></li>
<li><a class="post-section-overview" href="#heading-how-to-modify-dom-elements">How to Modify DOM Elements</a><br>– <a class="post-section-overview" href="#heading-how-to-manipulate-element-content-and-visibility">How to Manipulate Element Content and Visibility</a><br>– <a class="post-section-overview" href="#heading-how-to-modify-element-attributes">How to Modify Element Attributes</a><br>– <a class="post-section-overview" href="#heading-html-insertion-methods">HTML Insertion Methods</a><br>– <a class="post-section-overview" href="#heading-how-to-manipulate-classes-with-javascript">How to Manipulate Classes with JavaScript</a></li>
<li><a class="post-section-overview" href="#heading-event-handling-in-the-dom">Event Handling in the DOM</a><br>– <a class="post-section-overview" href="#heading-common-types-of-events">Common Types of Events</a><br>– <a class="post-section-overview" href="#heading-event-handlers">Event Handlers</a><br>– <a class="post-section-overview" href="#heading-event-propagation">Event Propagation</a><br>– <a class="post-section-overview" href="#heading-event-bubbling">Event Bubbling</a><br>– <a class="post-section-overview" href="#heading-event-delegation">Event Delegation</a></li>
<li><a class="post-section-overview" href="#heading-conclusion">Conclusion</a></li>
</ol>
<h2 id="heading-what-is-the-browser-object-model-bom">What is the Browser Object Model (BOM)?</h2>
<p>The Browser Object Model is like a set of tools provided by the browser itself. It's not part of the official DOM specification, but it's specific to web browsers. As a result, the objects and methods available in the BOM may vary between different browsers.</p>
<p>The BOM provides JavaScript access to browser-specific things like the browser's history, location, and browser window itself.</p>
<h3 id="heading-window-object">Window Object</h3>
<p>The <code>window</code> Object serves as a global object in the browser, representing the browser window and is the top-level object in JavaScript when we're working in a web browser. You can access it by typing <code>window</code> in the browser console:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">window</span>); <span class="hljs-comment">// prints the Window object</span>
</code></pre>
<p>Since, it's global, you can access it from anywhere and use it to access other global objects such as the console and the alert function.</p>
<p>The <code>window</code> object is a key part of the BOM and provides access to many browser-related things. For example, <code>window.location.href</code> gives you the URL of the current web page.</p>
<p>Functions like <code>alert()</code>, <code>prompt()</code>, and <code>confirm()</code> are also part of the BOM, allowing you to interact with users through pop-up dialogs.</p>
<h2 id="heading-what-is-the-document-object-model-dom">What is the Document Object Model (DOM)?</h2>
<p>The Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a web page, allowing interaction with its elements using programming languages like JavaScript.</p>
<p>The DOM contains the <code>document</code> object, which represents the DOM structure of the current web page and has properties and methods that allow you to manipulate the DOM.</p>
<p>You can access the <code>document</code> object by typing <code>document</code> in the browser console:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>); <span class="hljs-comment">// prints the DOM object</span>
</code></pre>
<p>You use <code>document</code> object to access and manipulate different parts of the HTML document. Elements within the DOM can be accessed using properties and methods of this object.</p>
<p>Examples include accessing the <code>body</code> or <code>title</code> element, retrieving HTML content (<code>innerHTML</code>), accessing text content (<code>innerText</code>) and changing <code>styles</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Accessing the document's title</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.title);

<span class="hljs-comment">// Changing the document's title</span>
<span class="hljs-built_in">document</span>.title = <span class="hljs-string">"changed Title"</span>;

<span class="hljs-comment">// Accessing the document's body </span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body);
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Changing background color of body element using inline CSS</span>
<span class="hljs-built_in">document</span>.body.style.backgroundColor = <span class="hljs-string">"red"</span>;
</code></pre>
<p>You can use the DOM to interact with web pages dynamically. This allows JavaScript to access, modify, and manipulate the content, structure, and style of a web document in response to user actions or other events. </p>
<p>Let's illustrate the concept of DOM manipulation with a simple example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"message"</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
      <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"changeText"</span>&gt;</span>Change Text<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-comment">// we select the paragraph element by its ID</span>
      <span class="hljs-keyword">let</span> messageElement = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"message"</span>);

      <span class="hljs-comment">// let's add event listener to button element using ID</span>
      <span class="hljs-built_in">document</span>
        .getElementById(<span class="hljs-string">"changeText"</span>)
        .addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span> (<span class="hljs-params"></span>) </span>{
          <span class="hljs-comment">// this  will change the text content of the paragraph element</span>
          messageElement.textContent = <span class="hljs-string">"Text Changed!"</span>;
        });
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this example, we have an HTML document with a <code>&lt;div&gt;</code> container containing a <code>&lt;p&gt;</code> element and a <code>&lt;button&gt;</code> element. </p>
<p>Using JavaScript, we can select the <code>&lt;p&gt;</code> element by its ID and attach an event listener to the <code>&lt;button&gt;</code> element. When the button is clicked, the text content of the paragraph element is changed dynamically.</p>
<h2 id="heading-dom-tree-structure">DOM Tree Structure</h2>
<p>The DOM represents the layout of HTML and XML documents as a tree-like structure, resembling the hierarchical arrangement of elements on a web page. In this tree, each node represents a part of the document, such as HTML elements, attributes, and text.</p>
<p>The top-level node in the tree is called the <strong>document node</strong>, which represents the entire HTML document. From there, it branches out to include all elements and their relationships within the document. Here's a visual representation of that:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/pic_htmltree-1.gif" alt="Image" width="600" height="400" loading="lazy">
<em>DOM Tree of Objects</em></p>
<h3 id="heading-types-of-nodes-in-the-dom-tree">Types of Nodes in the DOM Tree</h3>
<p>There are two main types of nodes in the DOM:</p>
<ol>
<li><strong>Element Nodes:</strong> Represent HTML elements such as <code>&lt;div&gt;</code>, <code>&lt;h1&gt;</code>, <code>&lt;p&gt;</code>, <code>&lt;span&gt;</code>, and so on. These nodes make up the backbone of the DOM tree and form the structure of the HTML document.</li>
<li><strong>Text Nodes:</strong> Represent text content within HTML elements. Text always serves as the last child (leaf node) of an element node and cannot contain any child nodes.</li>
</ol>
<p>In HTML, whitespace such as spaces, tabs, and line breaks are considered part of the text content within HTML elements and are represented as <strong>text nodes</strong>.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-62.png" alt="Image" width="600" height="400" loading="lazy">
<em>Linebreak is 1st child node, div (Blue) is 2nd, linebreak again 3rd</em></p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-64.png" alt="Image" width="600" height="400" loading="lazy">
<em>We can see all the nodes here including non-element ones (like text nodes or comment nodes)</em></p>
<p>We also have:</p>
<ul>
<li><strong>Attribute Nodes:</strong> Represent attributes of HTML elements, for example <code>id</code>, <code>class</code>, <code>src</code>, <code>href</code>, and so on.</li>
<li><strong>Comment Nodes:</strong> Nodes representing comments within the HTML markup.</li>
</ul>
<p>To access and manipulate DOM elements, we can "walk" through the tree structure using JavaScript. For instance:</p>
<ul>
<li><code>document.head</code>: Selects the <code>&lt;head&gt;</code> element of the current HTML document.</li>
<li><code>document.body</code>: Selects the <code>&lt;body&gt;</code> element of the current HTML document.</li>
<li><code>document.documentElement</code>: Selects the root element of the DOM tree, that is <code>&lt;html&gt;</code>.</li>
</ul>
<p>Once we access an element, we can modify its attributes or properties accordingly. For example, we can alter the background color of the <code>&lt;body&gt;</code> element to red by executing <code>document.body.style.backgroundColor = "red"</code> in the console.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-80.png" alt="Image" width="600" height="400" loading="lazy">
<em>We can see the body color has changed to "red"</em></p>
<h3 id="heading-node-relationships">Node Relationships</h3>
<p>Nodes in the DOM tree have parent-child relationships, which form the hierarchical structure of the tree. A child is an element that directly resides within another element (the parent).</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Hello, World!<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Click Me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>In the DOM tree, sibling elements are arranged linearly. The element to the right of the current element is called the next sibling, while the element to the left is called the previous sibling.</p>
<p>In the above example, the <code>&lt;p&gt;</code> element (previous sibling of ) and the <code>&lt;button&gt;</code> element (next sibling of </p><p>) are <strong>sibling nodes</strong> as they share the same parent. They are both <strong>children nodes</strong> of the <code>&lt;div&gt;</code> element with the ID "container". So the <code>&lt;div&gt;</code> element serves as the <strong>parent node</strong> of both the <code>&lt;p&gt;</code> and <code>&lt;button&gt;</code> elements.</p>
<p>Elements positioned above a given element in the DOM tree hierarchy are called ancestors. In the given code, the <code>&lt;html&gt;</code> element acts as the <strong>ancestor</strong> of the <code>&lt;body&gt;</code>, <code>&lt;h1&gt;</code>, and <code>&lt;p&gt;</code> elements, and they are <strong>descendants</strong> of the <code>&lt;html&gt;</code> element.</p>
<h2 id="heading-how-to-work-with-dom-elements">How to Work with DOM Elements</h2>
<p>Now, let's dive into accessing nodes in the DOM using various properties and methods.</p>
<h3 id="heading-traversing-the-dom">Traversing the DOM:</h3>
<p>When working with the Document Object Model (DOM), it's important to understand the distinction between element nodes (HTML elements) and non-element nodes (like text nodes, comments, and so on). Certain properties and methods specifically deal with either element nodes or all types of nodes, including non-element nodes.</p>
<p><strong>NodeList vs. HTMLCollection:</strong> Different properties return different collections of nodes. NodeList contains all types of nodes, while HTMLCollection specifically holds element nodes. Understanding this distinction is crucial for interpreting the results.</p>
<p><strong>Properties for All Nodes (Including Non-element Nodes):</strong> These properties return nodes of all types, including element nodes, text nodes, and comment nodes. </p>
<p><code>childNodes</code> returns a NodeList containing all child nodes and the <code>parentNode</code> property returns the parent node of the specified node. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Access the first child of the body node</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body.childNodes[<span class="hljs-number">0</span>]);


<span class="hljs-comment">// parentnode; the parent of a &lt;p&gt; element within a &lt;div&gt; would be the &lt;div&gt; itself.</span>
<span class="hljs-keyword">let</span> p = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>); <span class="hljs-comment">// Select the &lt;p&gt; element</span>
<span class="hljs-built_in">console</span>.log(p.parentNode); <span class="hljs-comment">// Output: &lt;div&gt; element (parent of p);</span>
</code></pre>
<p>Spaces between tags and line returns in HTML code are considered text nodes by the browser. So, the actual first child node might not be what you expect.</p>
<p><code>firstChild</code>/<code>lastChild</code>: Returns the first/last child node, again including all types.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.body.firstChild; <span class="hljs-comment">// Outputs: First child node (likely a linebreak(text node))</span>
<span class="hljs-built_in">document</span>.body.lastChild; <span class="hljs-comment">// Outputs: Last child node (likely a script tag)</span>
</code></pre>
<p>So we can say the following:</p>
<pre><code class="lang-javascript">element.childNodes[<span class="hljs-number">0</span>] === element.firstChild;
element.childNodes[element.childNodes.length - <span class="hljs-number">1</span>] === element.lastChild;
</code></pre>
<p><code>nextSibling</code>/<code>previousSibling</code>: returns the next sibling/previous sibling node,  including all of them.</p>
<p><strong>Element specific properties or Element only navigation</strong>: These properties provide a convenient way to access only element nodes, excluding text nodes and comments.</p>
<p><code>children</code> returns a live HTMLCollection of direct child elements, and the <code>parentElement</code> property returns the parent element node of the specified node.</p>
<p>In the below screenshot, you can see the difference between <code>childNodes</code> and <code>children</code>:</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-62.png" alt="Image" width="600" height="400" loading="lazy">
<em>Here, Linebreak (text node) will be considered 1st child node of body element, whereas div.color (Blue) will be considered the 1st child.</em></p>
<p>For instance, let's say we have this code:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// childnode</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body.childNodes);

<span class="hljs-comment">// children</span>
<span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.body.children);
</code></pre>
<pre><code><span class="hljs-comment">// childnode</span>
NodeList(<span class="hljs-number">19</span>) [text, div.color, text, div.color, text, comment, text, div.color, text, div.color, text, div.color, text, script, text, comment, text, script, text]


<span class="hljs-comment">// children</span>
HTMLCollection(<span class="hljs-number">7</span>) [div.color, div.color, div.color, div.color, div.color, script, script]
</code></pre><p>and, if we refresh the page, the output gets:</p>
<pre><code>NodeList(<span class="hljs-number">14</span>) [text, div.color, text, div.color, text, comment, text, div.color, text, div.color, text, div.color, text, script]
HTMLCollection(<span class="hljs-number">6</span>) [div.color, div.color, div.color, div.color, div.color, script]
</code></pre><p>Initially, the <code>NodeList</code> contains 19 nodes. These nodes consist of text nodes, <code>div</code> elements with the class "color", a comment node, and <code>script</code> elements. The <code>HTMLCollection</code> contains 7 elements, which are the <code>div</code> elements with the class "color" and <code>script</code> elements.</p>
<p>When the page is refreshed, some elements or nodes are removed or modified dynamically through JavaScript or other means, leading to the observed changes in the DOM structure.</p>
<p><code>firstElementChild</code>/<code>lastElementChild</code> returns the first/last child, excluding non-element nodes.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Both will exclude text nodes and comment nodes.</span>
<span class="hljs-built_in">document</span>.body.firstElementChild; <span class="hljs-comment">// Outputs: &lt;div class="color"&gt;</span>
<span class="hljs-built_in">document</span>.body.lastElementChild; <span class="hljs-comment">// Outputs: &lt;script src="script.js"&gt;</span>
</code></pre>
<p><strong>Key Points:</strong></p>
<ul>
<li>Choose the right property based on whether you need to target all nodes or specifically element nodes.</li>
<li>Remember that properties like <code>firstChild</code> and <code>previousSibling</code> might return element and non-element nodes, while their element-specific counterparts (<code>firstElementChild</code> and <code>previousElementSibling</code>) focus only on elements.</li>
</ul>
<h3 id="heading-methods-for-querying-dom-elements">Methods for Querying DOM Elements:</h3>
<p>JavaScript provides several methods for accessing elements in the DOM:</p>
<ul>
<li><strong><code>getElementById</code>:</strong> This method retrieves an element by its unique ID attribute.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myElement"</span>);
</code></pre>
<ul>
<li><strong><code>getElementsByClassName</code>:</strong> This method returns a collection of elements with the specified class name.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> elements = <span class="hljs-built_in">document</span>.getElementsByClassName(<span class="hljs-string">"myClass"</span>);
</code></pre>
<ul>
<li><strong><code>getElementsByTagName</code>:</strong> This method returns a list of collection of elements with the specified tag name.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> elements = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"div"</span>);
</code></pre>
<ul>
<li><strong><code>querySelector</code>:</strong> This method retrieves the first element that matches a specified CSS selector.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">"cssSelector"</span>);
</code></pre>
<ul>
<li><strong><code>querySelectorAll</code>:</strong>  This method retrieves all elements that match a CSS                 selector.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> elements = <span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">"cssSelector"</span>);
</code></pre>
<p>You might be wondering how <code>querySelector</code> differs from <code>querySelectorAll</code>.</p>
<p>Well, <code>querySelector</code> returns the first element within the document that matches the specified selector. On the other hand, <code>querySelectorAll</code> returns a static NodeList representing a list of the document's elements that match the specified group of selectors.</p>
<p>When you're using <code>querySelectorAll</code>, you receive a NodeList, which is similar to an array but not exactly the same. You cannot directly manupulate all elements like appling styles to all elements within a NodeList using methods like <code>style.backgroundColor = 'red'</code>. So we use a <code>forEach</code> loop. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">".box"</span>));

<span class="hljs-built_in">document</span>.querySelectorAll(<span class="hljs-string">'.box'</span>).forEach(<span class="hljs-function"><span class="hljs-params">element</span> =&gt;</span> {
    <span class="hljs-comment">// Within the forEach loop, we access each element and set its background color to green.</span>
    element.style.backgroundColor = <span class="hljs-string">"green"</span>;
});
</code></pre>
<p>Let's see what's going on in this code:</p>
<ul>
<li>In the first line, we directly change the background color of the element with the class 'box' using querySelector.</li>
<li>In the second line, we use querySelectorAll to select all elements with the class 'box' and log the NodeList to the console.</li>
<li>In third line, since <code>querySelectorAll</code> returns a NodeList, we need to iterate through each element in the NodeList in order to apply the background color to each element separately.</li>
<li>so  basically, we can say <code>querySelector</code> is equivalent to <code>querySelectorAll('section')[0]</code>.</li>
</ul>
<p>Alright, one last method to consider:</p>
<ul>
<li><strong><code>getElementsByName</code></strong>: This method returns a list of collection of elements with the specified name attribute.</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> items = <span class="hljs-built_in">document</span>.getElementsByName(<span class="hljs-string">'some-name-attribute'</span>);
<span class="hljs-built_in">console</span>.log(items);
</code></pre>
<p>These methods are important to understand because they are used in various situations. </p>
<p>For example, when we want to select all the <code>div</code> elements in the document, we can use the <code>querySelectorAll</code> method or the <code>getElementsByTagName</code> method. Both methods will return the same result, but <code>querySelectorAll</code> is more flexible because it can select elements that match any CSS selector. <code>getElementsByTagName</code> can only select elements that have the same tag name.</p>
<h3 id="heading-matches-closest-and-contains">Matches, Closest, and Contains:</h3>
<p>When you're working with JavaScript and dealing with web pages, you often need to find specific parts of the page or do things with them. Three methods you might use are <code>matches()</code>, <code>closest()</code>, and <code>contains()</code>.</p>
<p><strong><code>matches()</code></strong> checks if an element matches a certain style rule. For example, if you have a button and you want to see if it has a class of "active", you could use <code>button.matches('.active')</code>. It will return true if the button has that class, and false if it doesn't.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'button'</span>);
<span class="hljs-keyword">if</span> (button.matches(<span class="hljs-string">'.active'</span>)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The button is active'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The button is not active'</span>);
}
</code></pre>
<p>If you have an element and you want to find its nearest parent with a certain class, you can use <code>**closest()**</code> like this: <code>element.closest('.classname')</code>. </p>
<p>For instance, if you have a  link inside a list item and you want to find the nearest list item, you could do <code>link.closest('li')</code>.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> link = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'a'</span>);
<span class="hljs-keyword">const</span> listItem = link.closest(<span class="hljs-string">'li'</span>);
<span class="hljs-built_in">console</span>.log(listItem); <span class="hljs-comment">// This will give you the nearest list item</span>
</code></pre>
<p>And <strong><code>contains()</code></strong> checks if one element is inside another. For example, if you have a div and a paragraph inside it, you could check if the div contains the paragraph with <code>div.contains(paragraph)</code>. It will return true if the paragraph is inside the div, and false if it's not.</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> div = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'div'</span>);
<span class="hljs-keyword">const</span> paragraph = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'p'</span>);
<span class="hljs-keyword">if</span> (div.contains(paragraph)) {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The div contains a paragraph'</span>);
} <span class="hljs-keyword">else</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'The div does not contain any paragraph'</span>);
}
</code></pre>
<p>These methods are handy for navigating around your web page and doing different things with its elements.</p>
<h3 id="heading-how-to-inspect-dom-elements">How to Inspect DOM Elements</h3>
<p><strong>Using console.dir():</strong> <code>console.dir()</code> is not a method of the DOM. It's a method provided by the browser's Console API, specifically used for logging JavaScript objects to the console.</p>
<p>If we log an element using <code>console.log()</code>, we see its HTML representation. But with <code>console.dir()</code>, we get an interactive list showing all available attributes and functions for that element.</p>
<p><strong><code>tagName</code></strong> and <code>nodeName</code>: <code>tagName</code> is a property specific to HTML elements. It returns the tag name of an HTML element in uppercase letters. For example, if you have an HTML element <code>&lt;div&gt;</code>, <code>tagName</code> will return <code>"DIV"</code>.</p>
<p>On the other hand, <code>nodeName</code> is a property of DOM nodes that represents the name of the node. For element nodes, it returns the tag name in uppercase. For other types of nodes, it returns a string representing the type of node (for example, "#text" for text nodes, "#comment" for comment nodes).</p>
<p><strong>Discovering a node's type:</strong> Each node in the DOM has a <code>nodeType</code> property that indicates its type. It has a numeric value: <code>1</code> for elements, <code>2</code> for attributes, <code>3</code> for text nodes, <code>8</code> for comment and <code>9</code> for document. Read-only. This property can be used to distinguish between element nodes and text nodes. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> element = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
<span class="hljs-built_in">console</span>.log(element.nodeType); <span class="hljs-comment">// Output: 1</span>
</code></pre>
<h3 id="heading-table-navigation-in-the-dom">Table Navigation in the DOM</h3>
<p>Now, let's learn how to navigate a table element and its child nodes using the DOM. Here, instead of manually writing a table, we will use Bootstrap's pre-designed table.</p>
<p>Before diving into table navigation, let's discuss Bootstrap, a popular front-end framework offering pre-designed components and styles for building responsive web pages efficiently.</p>
<p>To integrate Bootstrap into our project, we'll:</p>
<ol>
<li>Copy the pre-designed table from <a target="_blank" href="https://getbootstrap.com/docs/5.3/content/tables/">here</a>.</li>
<li>Paste it into a container <code>&lt;div&gt;</code> in our HTML.</li>
<li>Include Bootstrap's CSS and JS files in our webpage (which you can copy from <a target="_blank" href="https://getbootstrap.com/docs/5.3/getting-started/introduction/">here</a>).</li>
</ol>
<p>Here's how our HTML code will look after integration:</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Table Navigation<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"styles.css"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/css/bootstrap.min.css"</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-KK94CHFLLe+nY2dmCWGMq91rCGa5gtU4mk92HdvYe+M/SXH301p5ILy+dN9+nJOZ"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
   <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
    <span class="hljs-comment">&lt;!-- Bootstrap Table --&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">table</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"table"</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- Table Header --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">thead</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>#<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>First<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>Last<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"col"</span>&gt;</span>Handle<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">thead</span>&gt;</span>
        <span class="hljs-comment">&lt;!-- Table Body --&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">tbody</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>1<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Mark<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Otto<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>@mdo<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>2<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Jacob<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>Thornton<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>@fat<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
          <span class="hljs-tag">&lt;<span class="hljs-name">tr</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">th</span> <span class="hljs-attr">scope</span>=<span class="hljs-string">"row"</span>&gt;</span>3<span class="hljs-tag">&lt;/<span class="hljs-name">th</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span> <span class="hljs-attr">colspan</span>=<span class="hljs-string">"2"</span>&gt;</span>Larry the Bird<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
            <span class="hljs-tag">&lt;<span class="hljs-name">td</span>&gt;</span>@twitter<span class="hljs-tag">&lt;/<span class="hljs-name">td</span>&gt;</span>
          <span class="hljs-tag">&lt;/<span class="hljs-name">tr</span>&gt;</span>
        <span class="hljs-tag">&lt;/<span class="hljs-name">tbody</span>&gt;</span>
      <span class="hljs-tag">&lt;/<span class="hljs-name">table</span>&gt;</span>
   <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"https://cdn.jsdelivr.net/npm/bootstrap@5.3.0-alpha3/dist/js/bootstrap.bundle.min.js"</span> <span class="hljs-attr">integrity</span>=<span class="hljs-string">"sha384-ENjdO4Dr2bkBIFxQpeoTz1HIcje39Wm4jDKdf19U8gI4ddQ3GYNS7NTKfAdVQSZe"</span> <span class="hljs-attr">crossorigin</span>=<span class="hljs-string">"anonymous"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h4 id="heading-table-navigation-properties">Table navigation properties:</h4>
<p>The table element supports various properties for convenient navigation, such as:</p>
<ul>
<li><code>table.rows</code>: Returns an HTMLCollection of all rows in the table.</li>
<li><code>table.caption</code>: Returns the caption element of the table.</li>
<li><code>table.tHead</code>: Returns the thead element of the table.</li>
<li><code>table.tFoot</code>: Returns the tfoot element of the table.</li>
<li><code>table.tBodies</code>: Returns an HTMLCollection of all tbody elements in the table.</li>
</ul>
<p>Similarly, the tr (table row) element supports properties like:</p>
<ul>
<li><code>tr.cells</code>: Returns an HTMLCollection of all cells in the row.</li>
<li><code>tr.sectionRowIndex</code>: Returns the index of the row in the current section (thead, tbody, or tfoot).</li>
<li><code>tr.rowIndex</code>: Returns the index of the row in the table.</li>
</ul>
<p>The td (table cell) element also supports the <code>td.cellIndex</code> property, returning the index of the cell in the row.</p>
<p>For instance, to print all rows in the table:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> t = <span class="hljs-built_in">document</span>.body.firstElementChild.firstElementChild; <span class="hljs-comment">// Selecting the table</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; t.rows.length; i++) {
    <span class="hljs-keyword">let</span> row = t.rows[i];
    <span class="hljs-built_in">console</span>.log(row)
}
</code></pre>
<p>To print cells in the first row:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> t = <span class="hljs-built_in">document</span>.body.firstElementChild.firstElementChild; <span class="hljs-comment">// Selecting the table</span>
<span class="hljs-keyword">let</span> row = t.rows[<span class="hljs-number">0</span>]; <span class="hljs-comment">// Selecting the first row</span>
<span class="hljs-keyword">for</span> (<span class="hljs-keyword">let</span> i = <span class="hljs-number">0</span>; i &lt; row.cells.length; i++) {
    <span class="hljs-keyword">let</span> cell = row.cells[i];
    <span class="hljs-built_in">console</span>.log(cell)
}
</code></pre>
<h2 id="heading-how-to-modify-dom-elements">How to Modify DOM Elements</h2>
<p>Once you have access to DOM elements, you can modify them in various ways using JavaScript.</p>
<h3 id="heading-how-to-manipulate-element-content-and-visibility">How to Manipulate Element Content and Visibility</h3>
<h4 id="heading-innerhtml-and-outerhtml"><code>innerHTML</code> and <code>outerHTML</code></h4>
<p>You can use <code>innerHTML</code> to access or change the HTML content inside an element as a string. <code>outerHTML</code>, on the other hand, lets you get or set the HTML content of an element as a string, including the original element itself.</p>
<p>Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    Hello World
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Hey I am span<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> first = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">"span"</span>)[<span class="hljs-number">0</span>]; <span class="hljs-comment">// </span>

<span class="hljs-comment">// log and change inner HTML</span>
<span class="hljs-built_in">console</span>.log(first.innerHTML); <span class="hljs-comment">// Output: Hey I am span</span>
first.innerHTML = <span class="hljs-string">"Hey I am changed"</span>; <span class="hljs-comment">// Modify the content of the &lt;span&gt; element</span>

<span class="hljs-comment">// log and change outer HTML</span>
<span class="hljs-built_in">console</span>.log(first.outerHTML); <span class="hljs-comment">// Output: &lt;span&gt;Hey I am span&lt;/span&gt;</span>
first.outerHTML = <span class="hljs-string">"&lt;h1&gt;Hey I am changed&lt;/h1&gt;"</span>; <span class="hljs-comment">// Reload the page to see the change</span>
</code></pre>
<h4 id="heading-textcontent-property"><code>textContent</code> property</h4>
<p>The <code>textContent</code> property allows you to set or retrieve the text content of an element, ignoring any HTML tags within it. It's useful when you want to update the text content of an element without affecting its HTML structure.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(first.textContent); <span class="hljs-comment">// output: Hey I am span</span>

<span class="hljs-comment">// change the text content</span>
first.textContent = <span class="hljs-string">"Hey I am changed"</span>;
</code></pre>
<h4 id="heading-innertext-property"><code>innerText</code> property</h4>
<p>The <code>innerText</code> property returns only the visible text content of an element, excluding any text within <code>&lt;script&gt;</code> and <code>&lt;style&gt;</code> elements, and accounting for CSS styling that affects visibility. It takes into account CSS styling, such as <code>display: none</code>, <code>visibility: hidden</code>, and so on and returns only the text that is rendered on the screen. </p>
<h4 id="heading-style-property"><code>style</code> property</h4>
<p>This property provides access to an object for manipulating an element's inline styles (for example, <code>element.style.color = "red"</code>).</p>
<h4 id="heading-hidden-property"><code>hidden</code> property</h4>
<p>The <code>hidden</code> provides a simple and convenient way to control the visibility of elements in the DOM without directly manipulating their style properties.</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'span'</span>)[<span class="hljs-number">0</span>].hidden = <span class="hljs-literal">true</span>;

<span class="hljs-comment">// When hidden is set to false, the element is visible.</span>
</code></pre>
<p>Note that setting an element's <code>hidden</code> property to <code>true</code> only hides it from view, but it still occupies space in the document layout. </p>
<h3 id="heading-how-to-modify-element-attributes">How to Modify Element Attributes</h3>
<p>The <code>getAttribute()</code> method retrieves the value of a specified attribute of an element, while <code>setAttribute()</code> sets or updates the value of a specified attribute. </p>
<p><code>hasAttribute()</code> checks whether an element has a specific attribute, returning true or false. The <code>removeAttribute()</code> method removes a specified attribute from an element.</p>
<p><img src="https://www.freecodecamp.org/news/content/images/2024/02/image-68.png" alt="Image" width="600" height="400" loading="lazy"></p>
<p>In HTML5, it's possible to define custom attributes for elements. But to prevent potential conflicts with future HTML or JavaScript updates, you should prefix custom attributes with <code>data-</code>. For instance:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"element1"</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"sample"</span> <span class="hljs-attr">data-category</span>=<span class="hljs-string">"music"</span> <span class="hljs-attr">data-rating</span>=<span class="hljs-string">"5"</span>&gt;</span>
    This is the first element.
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>To access these custom attributes using JavaScript, we can utilize the <code>dataset</code> property. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(element1.dataset);
</code></pre>
<p>This will display a <code>DOMStringMap</code> object containing all the custom attributes associated with the "element1" div. Specific custom attributes can also be accessed by their names. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(element1.dataset.category);

<span class="hljs-comment">// This code would output the value of the "category" custom attribute, which in this case is "music"</span>
</code></pre>
<h3 id="heading-html-insertion-methods">HTML Insertion Methods</h3>
<p>In HTML, there are several ways to insert new content or modify existing content dynamically using JavaScript. These are known as HTML insertion methods. </p>
<p>Consider the following HTML as our example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>first element<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h4 id="heading-classic-way-to-insert-html">Classic Way to Insert HTML:</h4>
<p>A conventional way to insert HTML is by using the <code>innerHTML</code> property. For example, let's say we want to add an <code>h1</code> element with the text "Hello World" inside the first <code>div</code>. We can do this using the following code:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'div'</span>)[<span class="hljs-number">0</span>];
a.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World&lt;/h1&gt;'</span>;
</code></pre>
<p>We could also append new HTML to the existing HTML inside the <code>div</code> element. For example:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// This will retain the old content and add a new h1 element.</span>
<span class="hljs-keyword">let</span> a = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'div'</span>)[<span class="hljs-number">0</span>];
a.innerHTML = a.innerHTML + <span class="hljs-string">'&lt;h1&gt;Hello World&lt;/h1&gt;'</span>;
</code></pre>
<h4 id="heading-using-createelement-to-insert-html">Using <code>createElement</code> to Insert HTML:</h4>
<p>Another method involves creating a new element using <code>createElement</code>, setting its content using <code>innerHTML</code>, and subsequently appending it to the target element using <code>appendChild</code>.</p>
<h4 id="heading-other-html-insertion-methods">Other HTML Insertion Methods:</h4>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
I am outside div (start)
<span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"container"</span>&gt;</span>
    I am start of this container
        <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>I am first element<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
    I am end of this container
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
I am outside div (end)
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span> <span class="hljs-attr">src</span>=<span class="hljs-string">"script.js"</span>&gt;</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Now, let's consider other methods for inserting HTML content dynamically:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> a = <span class="hljs-built_in">document</span>.getElementsByTagName(<span class="hljs-string">'div'</span>)[<span class="hljs-number">0</span>];

<span class="hljs-comment">// Using createElement and appendChild</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (append)&lt;/h1&gt;'</span>;
a.appendChild(div);

<span class="hljs-comment">// Using prepend</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (prepend)&lt;/h1&gt;'</span>;
a.prepend(div);

<span class="hljs-comment">// Using before</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (before)&lt;/h1&gt;'</span>;
a.before(div);

<span class="hljs-comment">// Using after</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (after)&lt;/h1&gt;'</span>;
a.after(div);

<span class="hljs-comment">// Using replaceWith</span>
<span class="hljs-keyword">let</span> div = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
div.innerHTML = <span class="hljs-string">'&lt;h1&gt;Hello World (replaced)&lt;/h1&gt;'</span>;
a.replaceWith(div);
</code></pre>
<p>This code demonstrates different methods for dynamically inserting HTML content into the DOM using JavaScript.</p>
<ul>
<li><code>a.append(div)</code>: This method appends the <code>div</code> element as the last child of the <code>a</code> element.</li>
<li><code>a.prepend(div)</code>: This method adds the <code>div</code> element as the first child of the <code>a</code> element.</li>
<li><code>a.before(div)</code>: This method adds the <code>div</code> element before the <code>a</code> element.</li>
<li><code>a.after(div)</code>: This method adds the <code>div</code> element after the <code>a</code> element.</li>
<li><code>a.replaceWith(div)</code>: This method replaces the <code>a</code> element with the <code>div</code> element.</li>
</ul>
<h3 id="heading-the-insertadjacenthtml-insertadjacentelement-and-insertadjacenttext-methods">The <code>insertAdjacentHTML</code>, <code>insertAdjacentElement</code>, and <code>insertAdjacentText</code> Methods</h3>
<p>These methods are used to insert content into the DOM at a specified position relative to a given element. They are helpful when you need to dynamically add new elements or text to your webpage.</p>
<h4 id="heading-insertadjacenthtml"><code>insertAdjacentHTML</code>:</h4>
<p><code>insertAdjacentHTML</code> allows you to insert a string of HTML at a specified position relative to the element.</p>
<p>The first parameter specifies where the HTML string will be inserted:</p>
<ul>
<li><code>beforebegin</code>: Before the element itself.</li>
<li><code>afterbegin</code>: Just inside the element, before its first child.</li>
<li><code>beforeend</code>: Just inside the element, after its last child.</li>
<li><code>afterend</code>: After the element itself.</li>
</ul>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
element.insertAdjacentHTML(<span class="hljs-string">'beforebegin'</span>, <span class="hljs-string">'&lt;div&gt;New content&lt;/div&gt;'</span>);
</code></pre>
<h4 id="heading-insertadjacentelement"><code>insertAdjacentElement</code>:</h4>
<p>It's similar to <code>insertAdjacentHTML</code>, but instead of inserting HTML, you can insert a DOM element.</p>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
<span class="hljs-keyword">let</span> newElement = <span class="hljs-built_in">document</span>.createElement(<span class="hljs-string">'div'</span>);
newElement.textContent = <span class="hljs-string">'New content'</span>;
element.insertAdjacentElement(<span class="hljs-string">'beforebegin'</span>, newElement);
</code></pre>
<h4 id="heading-insertadjacenttext"><code>insertAdjacentText</code>:</h4>
<p>It's similar to <code>insertAdjacentHTML</code>, but instead of inserting HTML, you can insert plain text.</p>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
element.insertAdjacentText(<span class="hljs-string">'beforebegin'</span>, <span class="hljs-string">'New content'</span>);
</code></pre>
<h4 id="heading-node-removal">Node Removal:</h4>
<p>The <code>remove</code> method removes the element from the DOM.</p>
<p>Example usage:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> element = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'example'</span>);
element.remove();
</code></pre>
<p>These methods allow you to manipulate the DOM dynamically, adding or removing content based on certain conditions or user interactions.</p>
<p>When using <code>insertAdjacentHTML</code>, <code>insertAdjacentElement</code>, or <code>insertAdjacentText</code>, you specify where the new content should be inserted relative to the given element.</p>
<p>When using <code>remove</code>, you simply remove the element from the DOM entirely.</p>
<p>These methods are helpful for dynamically updating the content of your webpage without having to reload the entire page.</p>
<h3 id="heading-how-to-manipulate-classes-with-javascript">How to Manipulate Classes with JavaScript</h3>
<p>In HTML, we use classes to group elements and apply styles using CSS. For example, we have a div with an id of "first" in our HTML.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"first"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">span</span>&gt;</span>Hello, this is text<span class="hljs-tag">&lt;/<span class="hljs-name">span</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<p>We also have CSS styles for classes like "yellow", "red", and "text-dark" to change background color and text color.</p>
<pre><code class="lang-css"><span class="hljs-selector-class">.yellow</span> {
    <span class="hljs-attribute">background-color</span>: yellow;
    <span class="hljs-attribute">color</span>: white;
}
<span class="hljs-selector-class">.red</span> {
    <span class="hljs-attribute">background-color</span>: red;
    <span class="hljs-attribute">color</span>: white;
}
<span class="hljs-selector-class">.text-dark</span> {
    <span class="hljs-attribute">color</span>: black;
}
</code></pre>
<p><strong><code>className</code>:</strong> In JavaScript, we can change the class of an element using the <code>className</code> property. For instance, if we want to change the class of the element with the id "first" to "red text-dark", we would do:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// we are applying 2 classes here</span>
first.className = <span class="hljs-string">"red text-dark"</span>;
</code></pre>
<p>If we want to add another class without removing the existing ones, we use the <code>+=</code> operator:</p>
<pre><code class="lang-javascript">first.className += <span class="hljs-string">" yellow"</span>; <span class="hljs-comment">// Adds the class "yellow" without removing existing classes</span>
</code></pre>
<p><strong><code>classList</code>:</strong> The <code>classList</code> property allows you to manipulate the classes of an element. We can use methods like <code>add</code>, <code>remove</code>, <code>toggle</code>, and <code>contains</code> to add, remove, toggle, or check the presence of a class.</p>
<ul>
<li><code>classList.remove()</code>: Removes a specific class from the element:</li>
</ul>
<pre><code class="lang-javascript">first.classList.remove(<span class="hljs-string">'text-dark'</span>); <span class="hljs-comment">// Removes the class "text-dark"</span>
</code></pre>
<ul>
<li><code>classList.add()</code>: But wait, it looked better with that class! We can also add it back with:</li>
</ul>
<pre><code class="lang-javascript">first.classList.add(<span class="hljs-string">'text-dark'</span>); <span class="hljs-comment">// Adds the class "text-dark"</span>
</code></pre>
<ul>
<li><code>classList.toggle()</code>: Toggles a class on or off based on its presence:</li>
</ul>
<pre><code class="lang-javascript">first.classList.toggle(<span class="hljs-string">'text-dark'</span>); <span class="hljs-comment">// Toggles the class "text-dark" (adds if absent, removes if present)</span>
</code></pre>
<ul>
<li><code>classList.contains()</code>: Checks if a class is present on the element:</li>
</ul>
<pre><code class="lang-javascript"><span class="hljs-built_in">console</span>.log(first.classList.contains(<span class="hljs-string">'text-dark'</span>)); <span class="hljs-comment">// Returns true if the class "text-dark" is present</span>
</code></pre>
<h2 id="heading-event-handling-in-the-dom">Event Handling in the DOM</h2>
<p>Events are actions or occurrences that happen in the system you are programming, that the system may need to respond to in some way. </p>
<p>In the context of web development, events (<strong>Browser Events</strong>) can be user interactions like clicks, mouse movements, key presses, and so on. JavaScript allows you to handle these events and perform actions in response to them.</p>
<p>In HTML, you can directly specify what should happen when an event occurs using attributes like <code>onclick</code>, <code>onmouseover</code>, and so on. For example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('hello')"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>While you can write JavaScript directly in HTML attributes, it's always better to keep your HTML clean and handle events in JavaScript code separately. This makes your code easier to read and maintain.</p>
<p>You can do this by selecting elements from the webpage using JavaScript and then attaching an event handler to them. Here's how you might do it:</p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> container = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"container"</span>);
container.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hey, this is logged from the script!"</span>);
}
</code></pre>
<p>In this code, we select the element with the id "container" using <code>document.getElementById()</code>. Then, we attach a function to the <code>onclick</code> event of that element. This function will be executed whenever the element is clicked.</p>
<h3 id="heading-common-types-of-events">Common Types of Events:</h3>
<ol>
<li><p><strong>Mouse Events</strong>: These events are related to interactions with the mouse. </p>
</li>
<li><p><strong>click</strong>: When you click on an element.</p>
</li>
<li><strong>contextmenu</strong>: When you right-click on an element.</li>
<li><strong>mouseover / mouseout</strong>: When the mouse cursor enters or leaves an element.</li>
<li><strong>mousedown / mouseup</strong>: When you press or release a mouse button over an element.</li>
<li><strong>mousemove</strong>: When the mouse is moved.</li>
</ol>
<p>Some Examples of Mouse Events:</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Mouse Button Property Example:</span>

&lt;div onmousedown=<span class="hljs-string">"console.log('Mouse button:', event.button)"</span>&gt;Click me&lt;/div&gt;
</code></pre>
<p>In this example, the event.button property is used to log which mouse button was pressed.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Modifier Keys Example:</span>

&lt;div onclick=<span class="hljs-string">"if(event.ctrlKey) console.log('Ctrl + Click!')"</span>&gt;Ctrl + Click Me&lt;/div&gt;
</code></pre>
<p>This example logs a message when the user clicks the element while holding the Ctrl key.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Coordinates Example:</span>

&lt;div onmousemove=<span class="hljs-string">"console.log('clientX:', event.clientX, 'clientY:', event.clientY)"</span>&gt;Move your mouse here&lt;/div&gt;
</code></pre>
<p>This example logs the clientX and clientY coordinates of the mouse pointer as it moves over the element.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Preventing Selection Example:</span>

&lt;span ondblclick=<span class="hljs-string">"console.log('Double clicked!')"</span> onmousedown=<span class="hljs-string">"return false;"</span>&gt;Double-click me&lt;/span&gt;
</code></pre>
<p>In this example, the return false statement in the onmousedown event handler prevents the default selection behavior when the element is double-clicked.</p>
<ol start="2">
<li><strong>Keyboard Events –</strong> <strong>keydown / keyup</strong>: When a key is pressed or released on the keyboard.</li>
</ol>
<p>Some Examples of Keyboard Events:</p>
<pre><code class="lang-javascript">&lt;input type=<span class="hljs-string">"text"</span> onkeydown=<span class="hljs-string">"console.log('Key pressed!')"</span> onkeyup=<span class="hljs-string">"console.log('Key released!')"</span>&gt;
</code></pre>
<p>In this example, the input field triggers events when a key is pressed (keydown) and released (keyup).</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Event Modifiers Example:</span>

&lt;input type=<span class="hljs-string">"text"</span> onkeydown=<span class="hljs-string">"if(event.ctrlKey &amp;&amp; event.key === 'c') console.log('Ctrl + C pressed!')"</span>&gt;
</code></pre>
<p>This example logs a message when the user presses the Ctrl key and 'c' key simultaneously in the input field.</p>
<pre><code class="lang-javascript"><span class="hljs-comment">// Accessing Key Information Example:</span>

&lt;input type=<span class="hljs-string">"text"</span> onkeydown=<span class="hljs-string">"console.log('Key pressed:', event.key)"</span>&gt;
</code></pre>
<p>This example logs the key that was pressed in the input field.</p>
<ol start="3">
<li><p><strong>Form Element Events</strong>: These events occur when you interact with form elements, like submitting a form, focusing on an input field, and so on.</p>
</li>
<li><p><strong>Document Events</strong>: These events are related to the document object itself. Example: <strong>DOMContentLoaded</strong> (when the HTML is fully loaded and the DOM is ready)</p>
</li>
<li><p><strong>CSS Events</strong>: These events are related to CSS animations. Example: <strong>transitionend</strong> (When a CSS animation finishes)</p>
</li>
</ol>
<p>Now, let's see an example demonstrating the practical application of event handling and input validation in web development:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">title</span>&gt;</span>Input Validation Example<span class="hljs-tag">&lt;/<span class="hljs-name">title</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">checkPhoneNumber</span>(<span class="hljs-params">event</span>) </span>{
  <span class="hljs-keyword">const</span> validKeys = [<span class="hljs-string">'0'</span>, <span class="hljs-string">'1'</span>, <span class="hljs-string">'2'</span>, <span class="hljs-string">'3'</span>, <span class="hljs-string">'4'</span>, <span class="hljs-string">'5'</span>, <span class="hljs-string">'6'</span>, <span class="hljs-string">'7'</span>, <span class="hljs-string">'8'</span>, <span class="hljs-string">'9'</span>, <span class="hljs-string">'+'</span>, <span class="hljs-string">'('</span>, <span class="hljs-string">')'</span>, <span class="hljs-string">'-'</span>];
  <span class="hljs-keyword">if</span> (!validKeys.includes(event.key)) {
    event.preventDefault(); <span class="hljs-comment">// Prevent default action for invalid keys</span>
  }
}
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">label</span> <span class="hljs-attr">for</span>=<span class="hljs-string">"phone"</span>&gt;</span>Enter Phone Number:<span class="hljs-tag">&lt;/<span class="hljs-name">label</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">input</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"tel"</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"phone"</span> <span class="hljs-attr">onkeydown</span>=<span class="hljs-string">"checkPhoneNumber(event)"</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">p</span>&gt;</span>Only digits, +, (, ), and - are allowed.<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>In this example, we're implementing input validation for a phone number input field. The <code>onkeydown</code> event triggers the <code>checkPhoneNumber</code> function, which checks if the pressed key is valid (digits, plus sign, parentheses, or hyphen). If the key is not valid, the default action (character input) is prevented.</p>
<p>You can <a target="_blank" href="https://www.freecodecamp.org/news/dom-events-and-javascript-event-listeners/">explore more about events here</a>.</p>
<h3 id="heading-event-handlers">Event Handlers</h3>
<p>To react to these events, we use event handlers. An event handler is simply a function that runs when a specific event occurs. There are different ways to assign event handlers in JavaScript:</p>
<ol>
<li><strong>HTML Attribute</strong>: You can set an event handler directly in the HTML code using an attribute like <code>onclick</code>, <code>onmouseover</code>, etc.</li>
</ol>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('Button clicked!')"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<ol start="2">
<li><strong>DOM Property</strong>: You can assign a handler using a DOM property like <code>onclick</code>, <code>onmouseover</code>, and so on.</li>
</ol>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">'Button clicked!'</span>);
  };
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<ol start="3">
<li><strong>Event Listeners</strong>: Event listeners are functions that wait for a specific event to occur and then execute a designated function. This is typically done using the <code>addEventListener</code> method. </li>
</ol>
<h3 id="heading-addeventlistener-and-removeeventlistener"><code>addEventListener()</code> and <code>removeEventListener()</code>:</h3>
<p>These are methods used to assign and remove event handlers, respectively, in JavaScript.</p>
<ul>
<li><code>**addEventListener()**</code> is used to attach an event listener to an element, which listens for a specific event (for example, a click or mouseover). It provides more flexibility, especially when you need to add multiple handlers to the same event.</li>
</ul>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">'Button clicked!'</span>);
  });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> btn = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'btn'</span>);

<span class="hljs-comment">// Example 1: Adding event listeners directly with anonymous functions</span>
btn.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">e</span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button clicked!"</span>); <span class="hljs-comment">// Logs a message when the button is clicked</span>
});

<span class="hljs-comment">// Example 2: Defining functions separately and then adding event listeners</span>
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">greet</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Hello!"</span>);
}
<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">farewell</span>(<span class="hljs-params"></span>) </span>{
    <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Goodbye!"</span>);
}
btn.addEventListener(<span class="hljs-string">'mouseenter'</span>, greet); <span class="hljs-comment">// Greets when the mouse enters the button</span>
btn.addEventListener(<span class="hljs-string">'mouseleave'</span>, farewell); <span class="hljs-comment">// Says goodbye when the mouse leaves the button</span>
</code></pre>
<p>With <code>addEventListener</code>, you can also specify additional options as a third argument. Some common options are:</p>
<ul>
<li><code>once</code>: A boolean value that specifies whether the event listener should be removed after it is invoked once.</li>
<li><code>capture</code>: A boolean value that specifies whether the event should be captured during the capturing phase. The capturing phase happens before the bubbling phase.</li>
</ul>
<p>For example:</p>
<pre><code class="lang-javascript">btn.addEventListener(<span class="hljs-string">'click'</span>, handleClick, { <span class="hljs-attr">once</span>: <span class="hljs-literal">true</span>, <span class="hljs-attr">capture</span>: <span class="hljs-literal">true</span> });
</code></pre>
<p>This will add a click event listener to the button element that is triggered only once and captures the event during the capturing phase.</p>
<ul>
<li><code>**removeEventListener()**</code> is used to remove a previously attached event listener from an element. </li>
</ul>
<pre><code class="lang-html">// Example 1

<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">handleClick</span>(<span class="hljs-params"></span>) </span>{
    alert(<span class="hljs-string">'Button clicked!'</span>);
  }

  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">'click'</span>, handleClick);
  <span class="hljs-comment">// Remove the event handler</span>
  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).removeEventListener(<span class="hljs-string">'click'</span>, handleClick);
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-comment">// Example 2</span>
<span class="hljs-comment">// Assume a user preference</span>
<span class="hljs-keyword">const</span> allowGreetings = <span class="hljs-literal">true</span>;

<span class="hljs-comment">// Removing event listeners based on user preference</span>
<span class="hljs-keyword">if</span> (!allowGreetings) {
    btn.removeEventListener(<span class="hljs-string">'mouseenter'</span>, greet);
}
</code></pre>
<h3 id="heading-object-handlers-handleevent">Object Handlers: <code>handleEvent</code></h3>
<p>Instead of assigning a function as an event handler, you can also assign an object that has a <code>handleEvent</code> method. When the event occurs, the <code>handleEvent</code> method of the object will be called.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myButton"</span>&gt;</span>Click me<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">let</span> myObject = {
    <span class="hljs-attr">handleEvent</span>: <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
      alert(<span class="hljs-string">'Button clicked!'</span>);
    }
  };

  <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myButton"</span>).addEventListener(<span class="hljs-string">'click'</span>, myObject);
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>In this example, when the button is clicked, the <code>handleEvent</code> method of <code>myObject</code> is called.</p>
<h3 id="heading-event-object">Event Object:</h3>
<p>When an event occurs, the browser creates an event object that contains information about the event, such as the type of event, the target element, and any additional data. </p>
<p>This object is passed as an argument to the event handler function which can be accessed within the callback function of an event listener.</p>
<pre><code class="lang-javascript">element.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-built_in">console</span>.log(event.type); <span class="hljs-comment">// Output: "click"</span>
    <span class="hljs-built_in">console</span>.log(event.target); <span class="hljs-comment">// Output: The element that was clicked</span>
     <span class="hljs-comment">// We can access more properties like event.clientX, event.clientY, etc.</span>
});
</code></pre>
<h3 id="heading-event-propagation">Event Propagation:</h3>
<p>Events in the DOM can propagate through the DOM tree in two phases: the capturing phase and bubbling phase. </p>
<p>When an event happens on an element, like a click or a key press, the browser needs to decide which elements should be notified about the event. </p>
<p>Event capturing and bubbling describe the order in which elements are notified about the event. Understanding event propagation is important when dealing with nested elements and event delegation.</p>
<ol>
<li><strong>Capturing Phase</strong>: In the capturing phase, the event starts from the top of the DOM hierarchy (usually the <code>&lt;html&gt;</code> element) and travels down to the target element. During this phase, event handlers attached with <code>addEventListener</code> and the <code>capture</code> option set to <code>true</code> are triggered. These handlers are executed before the event reaches the target element.</li>
<li><strong>Target Phase</strong>: Once the event reaches the target element, it enters the target phase. Event handlers attached with <code>addEventListener</code> without the <code>capture</code> option (or with <code>false</code> as the value) are triggered during this phase. Handlers attached in this phase are executed when the event is directly targeting the element.</li>
<li><strong>Bubbling Phase</strong>: After the target phase, the event bubbles up from the target element to the top of the DOM hierarchy. During this phase, event handlers attached with <code>addEventListener</code> without the <code>capture</code> option (or with <code>false</code> as the value) are triggered again. Handlers attached in this phase are executed as the event travels up from the target element.</li>
</ol>
<p>Let's look at an example. Consider a <code>&lt;div&gt;</code> nested inside another <code>&lt;div&gt;</code>. If a click event occurs on the inner <code>&lt;div&gt;</code>, the capturing phase starts from the outer <code>&lt;div&gt;</code> and goes down to the inner <code>&lt;div&gt;</code>. Then, the target phase happens on the inner <code>&lt;div&gt;</code>, and finally, the bubbling phase occurs from the inner <code>&lt;div&gt;</code> back up to the outer <code>&lt;div&gt;</code>.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"outerDiv"</span>&gt;</span>
  Outer Div
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"innerDiv"</span>&gt;</span>Inner Div<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>

<span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
  <span class="hljs-keyword">const</span> outerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'outerDiv'</span>);
  <span class="hljs-keyword">const</span> innerDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'innerDiv'</span>);

  outerDiv.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Capturing: Outer Div'</span>), <span class="hljs-literal">true</span>);
  innerDiv.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Target: Inner Div'</span>));
  outerDiv.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Bubbling: Outer Div'</span>));
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span>
</code></pre>
<p>Let's understand Bubbling in detail.</p>
<h3 id="heading-event-bubbling">Event Bubbling:</h3>
<p>Event bubbling is a mechanism in JavaScript where, when an event occurs on an element, such as a click, that event first triggers on the target element and then "bubbles" up through its ancestor elements all the way up to the root of the document (usually <code>&lt;html&gt;</code>). This triggers the same event on each ancestor along the way. Here's an example:</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">form</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('form')"</span>&gt;</span>
  FORM
  <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('div')"</span>&gt;</span>
    DIV
    <span class="hljs-tag">&lt;<span class="hljs-name">p</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('p')"</span>&gt;</span>P<span class="hljs-tag">&lt;/<span class="hljs-name">p</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">form</span>&gt;</span>
</code></pre>
<p>If you click on the <code>&lt;p&gt;</code> element, the click event will first trigger on the <code>&lt;p&gt;</code> element, then on the <code>&lt;div&gt;</code>, and finally on the <code>&lt;form&gt;</code>. This is because the event bubbles up through each parent element in the DOM hierarchy.</p>
<p><strong><code>event.target</code></strong> vs. <code>this</code>:</p>
<ul>
<li><code>event.target</code> refers to the element that initiated the event. It remains the same throughout the bubbling process. In the above example, if you click on the <code>&lt;p&gt;</code> element, <code>event.target</code> will be the <code>&lt;p&gt;</code> element.</li>
<li><code>this</code> (or <code>event.currentTarget</code>) refers to the current element that the event handler is attached to. In the above example, if the event handler is attached to the <code>&lt;form&gt;</code>, <code>this</code> will be the <code>&lt;form&gt;</code> element.</li>
</ul>
<h4 id="heading-how-to-stop-event-bubbling">How to stop event bubbling:</h4>
<p>Sometimes, you might want to stop the event from bubbling up further. You can do this using the <code>event.stopPropagation()</code> method. This method stops the event from propagating to parent elements.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">body</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"alert('the bubbling doesn't reach here')"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span>=<span class="hljs-string">"event.stopPropagation()"</span>&gt;</span>Click here<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
</code></pre>
<p>In this example, clicking the button won't trigger the <code>alert</code> on the body element because <code>event.stopPropagation()</code> is called in the button's click event handler.</p>
<p><code>event.stopImmediatePropagation()</code> is similar to <code>event.stopPropagation()</code>, but also prevents other handlers on the current element from executing.</p>
<h3 id="heading-event-delegation">Event Delegation:</h3>
<p>Event delegation is a technique that allows you to handle events more efficiently by attaching a single event listener to a parent element instead of attaching multiple event listeners to individual child elements. This is particularly useful when you have a large number of similar elements that need the same event handling logic.</p>
<pre><code class="lang-javascript">parentElement.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
    <span class="hljs-keyword">if</span> (event.target.classList.contains(<span class="hljs-string">'childElement'</span>)) {
        <span class="hljs-comment">// Action to be performed when a child element is clicked</span>
    }
});
</code></pre>
<pre><code class="lang-javascript">&lt;!-- Example: Event delegation --&gt;
<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">ul</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"myList"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Item 1<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Item 2<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">li</span>&gt;</span>Item 3<span class="hljs-tag">&lt;/<span class="hljs-name">li</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">ul</span>&gt;</span></span>

<span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
    <span class="hljs-comment">// Adding a click event listener to the parent ul element</span>
    <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"myList"</span>).addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params">event</span>) </span>{
        <span class="hljs-comment">// Checking if the clicked element is an li</span>
        <span class="hljs-keyword">if</span> (event.target.tagName === <span class="hljs-string">"LI"</span>) {
            <span class="hljs-comment">// Code to execute when an li is clicked</span>
            <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Item clicked:"</span>, event.target.textContent);
        }
    });
</span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span></span>
</code></pre>
<p>This approach reduces the number of event listeners and improves performance.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>The DOM, or Document Object Model, is an interface that represents the structure of HTML documents. It serves as the bridge between JavaScript code and the browser, allowing manipulation of HTML elements, styles, attributes, and event handling. </p>
<p>The DOM API provides methods and properties to interact with the DOM tree. Examples include <code>querySelector</code>, <code>addEventListener</code>, <code>createElement</code>, <code>innerHTML</code>, <code>textContent</code>, etc.</p>
<p>Through DOM manipulation, developers can dynamically change various aspects of a web page, including text content, HTML attributes, and the structure of the document itself (for example, inserting, updating, or deleting HTML elements).</p>
<p>JavaScript frameworks and libraries like React often utilize DOM manipulation capabilities to efficiently manage and update user interfaces. This lets developers create complex web applications with interactive and responsive user experiences.</p>
<p>To learn more about the DOM, here are a few resources you can check out:</p>
<p>First of all, I wrote a follow-up article, which you can find here:<br><a class="post-section-overview" href="#https://www.freecodecamp.org/news/form-validation-in-javascript/">Client-Side Form Handling with JavaScript</a>.</p>
<p>You can also read more in the following articles:</p>
<ul>
<li><a target="_blank" href="https://www.samyakinfo.tech/blog/document-and-resource-loading">DOM Events Lifecycle and Efficient script Loading</a></li>
<li>The <a target="_blank" href="https://www.freecodecamp.org/news/the-javascript-dom-manipulation-handbook/">JavaScript DOM manipulation handbook</a></li>
<li>The <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/API/Document_Object_Model">MDN</a> web docs</li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/dom-manipulation-best-practices/">JavaScript DOM manipulation best practices</a></li>
<li><a target="_blank" href="https://www.freecodecamp.org/news/learn-javascript-for-dom-manipulation-in-spanish-course-for-beginners/">JS DOM manipulation in Spanish - full course</a></li>
</ul>
<p></p> ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Browser Events Explained in Plain English ]]>
                </title>
                <description>
                    <![CDATA[ What are browser events? An event refers to an action or occurrence that happens in the system you are programming. The system then notifies you about the event so that you can respond to it in some way if necessary. In this article, I will focus on ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-events-explained-in-simple-english/</link>
                <guid isPermaLink="false">66d45f6f38f2dc3808b790cb</guid>
                
                    <category>
                        <![CDATA[ beginners guide ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 29 Dec 2020 21:14:43 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/12/events.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-what-are-browser-events">What are browser events?</h2>
<p>An <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Learn/JavaScript/Building_blocks/Events">event</a> refers to an action or occurrence that happens in the system you are programming. The system then notifies you about the event so that you can respond to it in some way if necessary.</p>
<p>In this article, I will focus on events in the context of web browsers. Essentially, an event is an indicator which shows that a certain action has taken place so that you can make an appropriate response.</p>
<p>To illustrate what I am talking about, let's imagine that you are standing at a pedestrian crossing waiting for traffic lights to change so that you can safely cross the road. The event is the change in traffic light which makes you subsequently take an action – which, in this case, is crossing the road.</p>
<p>Similarly in web development, we can take an action whenever an event we have interest in takes place.</p>
<p>Some of the common events you might have come across in web development include:</p>
<ol>
<li>Mouse events</li>
</ol>
<ul>
<li><p><code>click</code></p>
</li>
<li><p><code>dblclick</code></p>
</li>
<li><p><code>mousemove</code></p>
</li>
<li><p><code>mouseover</code></p>
</li>
<li><p><code>mousewheel</code></p>
</li>
<li><p><code>mouseout</code></p>
</li>
<li><p><code>contextmenu</code></p>
</li>
<li><p><code>mousedown</code></p>
</li>
<li><p><code>mouseup</code></p>
</li>
</ul>
<ol start="2">
<li>Touch events</li>
</ol>
<ul>
<li><p><code>touchstart</code></p>
</li>
<li><p><code>touchmove</code></p>
</li>
<li><p><code>touchend</code></p>
</li>
<li><p><code>touchcancel</code></p>
</li>
</ul>
<ol start="3">
<li>Keyboard events</li>
</ol>
<ul>
<li><p><code>keydown</code></p>
</li>
<li><p><code>keypress</code></p>
</li>
<li><p><code>keyup</code></p>
</li>
</ul>
<ol start="4">
<li>Form events</li>
</ol>
<ul>
<li><p><code>focus</code></p>
</li>
<li><p><code>blur</code></p>
</li>
<li><p><code>change</code></p>
</li>
<li><p><code>submit</code></p>
</li>
</ul>
<ol start="5">
<li>Window events</li>
</ol>
<ul>
<li><p><code>scroll</code></p>
</li>
<li><p><code>resize</code></p>
</li>
<li><p><code>hashchange</code></p>
</li>
<li><p><code>load</code></p>
</li>
<li><p><code>unload</code></p>
</li>
</ul>
<p>For a complete list of events and the different categories they fall into, you can check out the <a target="_blank" href="https://developer.mozilla.org/en-US/docs/Web/Events">MDN documentation</a>. Some of the events listed are standard events in official specifications, while others are events used internally by specific browsers.</p>
<h2 id="heading-what-are-event-handlers">What are event handlers?</h2>
<p>As mentioned above, we monitor events so that whenever we receive a notification that the event has occurred, the program can take the appropriate action.</p>
<p>This action is often taken in functions called <strong>event handlers</strong> which are also referred to as <strong>event listeners</strong>. If an event occurs and the event handler is invoked, we say an event has been registered. This is illustrated in the code below.</p>
<p>If the button with <code>id</code> <code>btn</code> is clicked, the event handler is invoked and an alert with the text "Button has been clicked" is displayed. The <code>onclick</code> property has been assigned to a function which is the event handler. This is one of three ways of adding an event handler to a DOM element.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"btn"</span>);
button.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
   alert(<span class="hljs-string">"Button has been clicked"</span>);
}
</code></pre>
<p>It is worth pointing out that <strong>event handlers</strong> are mostly declared as functions, but they can also be objects.</p>
<h2 id="heading-how-to-assign-event-handlers">How to assign event handlers</h2>
<p>There are multiple ways of attaching event handlers to HTML elements. We'll discuss these methods, along with their pros and cons, below.</p>
<h3 id="heading-assign-an-event-handler-with-an-html-attribute">Assign an event handler with an HTML attribute</h3>
<p>This is the easiest way of attaching an event handler to HTML elements, though it is the least recommended. It involves using an inline HTML event attribute named <code>on&lt;event&gt;</code> whose value is the event handler. For example <code>onclick</code>, <code>onchange</code>, <code>onsubmit</code> and so on.</p>
<p>Take note that it is not uncommon to find HTML event attributes named <code>onClick</code>, <code>onChange</code> or <code>onSubmit</code> because HTML attributes are not case sensitive. Essentially it is syntactically correct to use <code>onclick</code>, <code>onClick</code> or <code>ONCLICK</code>. But it's common practice to leave it in lowercase.</p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span> = <span class="hljs-string">"alert('Hello world!')"</span>&gt;</span> Click Me <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span> = <span class="hljs-string">"(() =&gt; alert('Hello World!'))()"</span>&gt;</span> Click Me Too <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span> = <span class="hljs-string">"(function(){alert('Hello World!')})()"</span>&gt;</span> And Me <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
</code></pre>
<p>In the above example, JavaScript code has been literally assigned to the HTML event attribute.</p>
<p>Take note of the Immediately Invoked Function Expression (IIFE) format in the last two <code>button</code> elements. Though this appears easy and straightforward, assigning an inline HTML event attribute is inefficient and difficult to maintain.</p>
<p>Assume you have over 20 such buttons in your markup. It would be repetitive to write the same JavaScript code for each button. It is always better to write JavaScript in its own file so that you can easily use the same code for multiple HTML files.</p>
<p>Besides, you cannot have multiple lines of JavaScript code inline. Inline JavaScript code is considered an anti-pattern due to the aforementioned reasons. So try to avoid it unless you are trying out something quick.</p>
<h3 id="heading-declare-an-event-handler-in-a-script-tag">Declare an event handler in a <code>script</code> tag</h3>
<p>Instead of doing the above, you can also declare the event handler in a <code>script</code> tag and invoke it inline as shown below.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./index.css"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onClickHandler</span>(<span class="hljs-params"></span>)</span>{
         alert(<span class="hljs-string">"Hello world!"</span>);
       }
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> 
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"wrapper"</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">button</span> <span class="hljs-attr">onclick</span> = <span class="hljs-string">"onClickHandler()"</span>&gt;</span> Click me <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<p>Notice, though, that simply assigning the function name as a value of the HTML event attribute like <code>onclick = "onClickHandler"</code> will not work. You need to invoke it as shown above, enclosing the invocation in quotes just like the value of any HTML attribute.</p>
<h3 id="heading-assign-an-event-handler-using-the-dom-property">Assign an event handler using the DOM property</h3>
<p>Instead of using inline HTML event attribute illustrated above, you can also assign the event handler as the value of an event property on the DOM element. This is only possible inside a <code>script</code> tag or in a JavaScript file.</p>
<p>One limitation of this approach is that you cannot have multiple event handlers for the same event. If you have multiple handlers for the same event, as illustrated below, only the last one will be applied. The others will be overwritten.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"btn"</span>);
button.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
   alert(<span class="hljs-string">"Button has been clicked"</span>);
}
<span class="hljs-comment">// Only this is applied</span>
button.onclick = <span class="hljs-function"><span class="hljs-keyword">function</span>(<span class="hljs-params"></span>)</span>{
   <span class="hljs-built_in">console</span>.log(<span class="hljs-string">"Button has been clicked"</span>);
}
</code></pre>
<p>If you want to remove the event listener from the <code>onclick</code> event, you can simply re-assign <code>button.onclick</code> to <code>null</code>.</p>
<pre><code class="lang-js">button.onclick = <span class="hljs-literal">null</span>
</code></pre>
<h3 id="heading-how-to-improve-the-dom-method-of-adding-event-listeners">How to improve the DOM method of adding event listeners</h3>
<p>The above method of adding event listeners is preferable to using inline JavaScript. Still, it has a limitation of restricting an element to have only one event handler for each event.</p>
<p>For example you cannot apply multiple event handlers for a click event on an element.</p>
<p>To remedy this limitation, <code>addEventListener</code> and <code>removeEventListener</code> were introduced. This enables you to add multiple event handlers for the same event on the same element.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'btn'</span>);
button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  alert(<span class="hljs-string">'Hello World'</span>);
})
button.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function">() =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Hello World'</span>);
})
</code></pre>
<p>In the code above, an element with <code>id</code> <code>btn</code> is selected and then monitored for a <code>click</code> event by attaching two event handlers. The first event handler will be invoked and an alert message of <code>Hello World</code> pops up. Subsequently <code>Hello World</code> will also be logged in the console.</p>
<p>As you might have noticed from the above examples, the function signature of <code>element.addEventListener</code> is:</p>
<pre><code class="lang-js">element.addEventListener(event, eventHandler, [optional parameter])
</code></pre>
<h4 id="heading-parameters-to-the-addeventlistener-method">Parameters to the <code>addEventListener</code> method</h4>
<ol>
<li><strong>event</strong></li>
</ol>
<p>The first parameter, <code>event</code> (which is a required parameter) is a string that specifies the name of the event. For example <code>"click"</code>, <code>"mouseover"</code>, <code>"mouseout"</code> and so on.</p>
<ol start="2">
<li><strong>eventHandler</strong></li>
</ol>
<p>The second parameter, which like the first is also required, is a function which is invoked when the event occurs. An event object is passed as its first parameter. The event object depends on the type of event. For example, a <code>MouseEvent</code> object is passed for a click event.</p>
<ol start="3">
<li><strong>Optional parameter</strong></li>
</ol>
<p>The third parameter, which is an optional parameter, is an object with the properties:</p>
<ul>
<li><p><code>once</code>: Its value is a boolean. If <code>true</code>, the listener is removed after it triggers.</p>
</li>
<li><p><code>capture</code>: Its value is also a boolean. It sets the phase where it should handle the event, which is either in the bubbling or capturing phase. The default value is <code>false</code> , therefore the event is captured in the bubbling phase. You can read more about it <a target="_blank" href="https://javascript.info/bubbling-and-capturing">here</a>. For historical reasons, options can also be <code>true</code> or <code>false</code>.</p>
</li>
<li><p><code>passive</code>: Its value is also a boolean. If it is <code>true</code>, then the handler will not call <code>preventDefault()</code>. <code>preventDefault()</code> is a method of the event object.</p>
</li>
</ul>
<p>Similarly if you want to stop monitoring the <code>click</code> event, you can use <code>element.removeEventListener</code>. But this only works if the event listener has been registered using <code>element.addEventListener</code>. The function signature is similar to that of <code>element.addEventListener</code>.</p>
<pre><code class="lang-js">element.removeEventListener(event, eventHandler, [options])
</code></pre>
<p>For us to use <code>element.removeEventListener</code> to remove an <code>event</code>, the function passed as second argument to <code>element.addEventListener</code> must be a named function when adding the event listener. This ensures that the same function can be passed to <code>element.removeEventListener</code> if we want to remove it.</p>
<p>It is also worth mentioning here that, if you passed the optional arguments to the event handler, then you must also pass the same optional arguments to the <code>removeEventListener</code>.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">'btn'</span>);
button.removeEventListener(<span class="hljs-string">'click'</span>, clickHandler)
</code></pre>
<h2 id="heading-what-are-event-objects">What are event objects?</h2>
<p>An event handler has a parameter called <strong>event object</strong> which holds additional information about the event.</p>
<p>The information stored in the <strong>event object</strong> depends on the type of event. For example, the <strong>event object</strong> passed to a <code>click</code> event handler has a property called <code>target</code> which references the element from which the click event originated.</p>
<p>In the example below, if you click the element with <code>id</code> <code>btn</code>, <code>event.target</code> will reference it. All click event handlers are passed an <strong>event object</strong> with the <code>target</code> property. As already pointed out, different events have <strong>event object</strong> parameters which store different information.</p>
<pre><code class="lang-js"><span class="hljs-keyword">const</span> button = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"btn"</span>);
button.addEventListener(<span class="hljs-string">"click"</span>, <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(event.target);
})
</code></pre>
<h2 id="heading-the-value-of-this">The value of <code>this</code></h2>
<p>In an <code>event</code> handler, the value of <code>this</code> is the element on which the event handler is registered. Take note that the element on which the event handler is registered may not necessarily be the same as the element on which the event occurred.</p>
<p>For example in the code below, the event handler is registered on the wrapper. Normally, the value of <code>this</code> is the same as <code>event.currentTarget</code>. If you click the <code>button</code>, the value of <code>this</code> inside <code>onClickHandler</code> is the <code>div</code> not the <code>button</code> because it is the <code>div</code> on which the event handler is registered though the click originated from the button.</p>
<p>This is called <code>event propagation</code>. It is a very important concept which you can read about <a target="_blank" href="https://www.sitepoint.com/event-bubbling-javascript/">here</a> if you are interested.</p>
<pre><code class="lang-html"><span class="hljs-meta">&lt;!DOCTYPE <span class="hljs-meta-keyword">html</span>&gt;</span>
<span class="hljs-tag">&lt;<span class="hljs-name">html</span> <span class="hljs-attr">lang</span>=<span class="hljs-string">"en-US"</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">head</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">charset</span>=<span class="hljs-string">"utf-8"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">meta</span> <span class="hljs-attr">name</span>=<span class="hljs-string">"viewport"</span> <span class="hljs-attr">content</span>=<span class="hljs-string">"width=device-width, initial-scale=1"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">link</span> <span class="hljs-attr">rel</span>=<span class="hljs-string">"stylesheet"</span> <span class="hljs-attr">href</span>=<span class="hljs-string">"./index.css"</span> <span class="hljs-attr">type</span>=<span class="hljs-string">"text/css"</span> /&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">script</span>&gt;</span><span class="javascript">
      <span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">onClickHandler</span>(<span class="hljs-params"></span>)</span>{
         <span class="hljs-built_in">console</span>.log(<span class="hljs-built_in">this</span>)
         alert(<span class="hljs-string">"Hello world!"</span>);
       }
       <span class="hljs-keyword">const</span> wrapper = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">".wrapper"</span>);
       wrapper.addEventListener(<span class="hljs-string">"click"</span>, onClickHandler);
    </span><span class="hljs-tag">&lt;/<span class="hljs-name">script</span>&gt;</span> 
  <span class="hljs-tag">&lt;/<span class="hljs-name">head</span>&gt;</span>
  <span class="hljs-tag">&lt;<span class="hljs-name">body</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">class</span>=<span class="hljs-string">"wrapper"</span>&gt;</span>
       <span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span> Click me <span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span>
    <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">body</span>&gt;</span>
<span class="hljs-tag">&lt;/<span class="hljs-name">html</span>&gt;</span>
</code></pre>
<h2 id="heading-conclusion">Conclusion</h2>
<p>In this article we looked at:</p>
<ul>
<li><p>Browser events and what they are</p>
</li>
<li><p>Different ways of adding event handlers to DOM elements</p>
</li>
<li><p>Event object parameters to event handlers</p>
</li>
<li><p>The value of <code>this</code> in an event handler</p>
</li>
</ul>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Event Handlers – How to Handle Events in JS ]]>
                </title>
                <description>
                    <![CDATA[ What are events? Events are actions that happen when a user interacts with the page - like clicking an element, typing in a field, or loading a page.  The browser notifies the system that something has happened, and that it needs to be handled. It ge... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-event-handlers/</link>
                <guid isPermaLink="false">66b99ced3cd81de09c96b2d1</guid>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ Shruti Kapoor ]]>
                </dc:creator>
                <pubDate>Mon, 21 Sep 2020 17:09:50 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2020/09/samuel-pereira-uf2nnANWa8Q-unsplash.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <h2 id="heading-what-are-events">What are events?</h2>
<p>Events are actions that happen when a user interacts with the page - like clicking an element, typing in a field, or loading a page. </p>
<p>The browser notifies the system that something has happened, and that it needs to be handled. It gets handled by registering a function, called an <code>event handler</code>, that listens for a particular type of event. </p>
<h2 id="heading-what-does-it-mean-to-handle-an-event">What does it mean to "handle an event"?</h2>
<p>To put it in simple terms, consider this - let's assume you are interested in attending Web Development meetup events in your local community. </p>
<p>To do this, you sign-up for a local meetup called "Women Who Code" and subscribe to notifications. This way, anytime a new meetup is scheduled, you get alerted. That is event handling! </p>
<p>The "event" here is a new JS meetup. When a new meetup is posted, the website meetup.com catches this change, thereby "handling" this event. It then notifies you, thus taking an "action" on the event. </p>
<p>In a browser, events are handled similarly. The browser detects a change, and alerts a function (event handler) that is listening to a particular event. These functions then perform the actions as desired. </p>
<p>Let's look at an example of a <code>click</code> event handler:</p>
<pre><code>&lt;div <span class="hljs-class"><span class="hljs-keyword">class</span></span>=<span class="hljs-string">"buttons"</span>&gt;
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Press 1<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Press 2<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
  <span class="xml"><span class="hljs-tag">&lt;<span class="hljs-name">button</span>&gt;</span>Press 3<span class="hljs-tag">&lt;/<span class="hljs-name">button</span>&gt;</span></span>
&lt;/div&gt;
<span class="hljs-keyword">const</span> buttonContainer = <span class="hljs-built_in">document</span>.querySelector(<span class="hljs-string">'.buttons'</span>);
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'buttonContainer'</span>, buttonContainer);

buttonContainer.addEventListener(<span class="hljs-string">'click'</span>, <span class="hljs-function"><span class="hljs-params">event</span> =&gt;</span> {
  <span class="hljs-built_in">console</span>.log(event.target.value)
})
</code></pre><h2 id="heading-what-are-the-different-types-of-events">What are the different types of events?</h2>
<p>An event can be triggered any time a user interacts with the page. These events could be a user scrolling through the page, clicking on an item, or loading a page. </p>
<p>Here are some common events - <code>onclick</code> <code>dblclick</code> <code>mousedown</code> <code>mouseup</code> <code>mousemove</code> <code>keydown</code> <code>keyup</code> <code>touchmove</code> <code>touchstart</code> <code>touchend</code> <code>onload</code> <code>onfocus</code> <code>onblur</code> <code>onerror</code> <code>onscroll</code> </p>
<h2 id="heading-different-phases-of-events-capture-target-bubble">Different phases of events - capture, target, bubble</h2>
<p>When an event moves through the DOM - whether bubbling up or trickling down - it is called event propagation. The event propagates through the DOM tree. </p>
<p>Events happen in two phases: the bubbling phase and the capturing phase. </p>
<p>In capture phase, also called the trickling phase, the event "trickles down" to the element that caused the event. </p>
<p>It starts from the root level element and handler, and then propagates down to the element. The capture phase is completed when the event reaches the <code>target</code>. </p>
<p>In the bubble phase, the event is "bubbled" up to the DOM tree. It is first captured and handled by the innermost handler (the one that is closest to the element on which the event occurred). It then bubbles up (or propagates up) to the higher levels of DOM tree, further up to its parents, and then finally to its root. </p>
<p>Her's a trick to help you remember this:</p>
<pre><code>trickle down, bubble up
</code></pre><p>Here's an infographic from <a target="_blank" href="https://www.quirksmode.org/js/events_order.html">quirksmode</a> that explains this very well: </p>
<pre><code>               / \
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  | |          |     |
|   -------------------------     |
|        Event BUBBLING           |
-----------------------------------

               | |
---------------| |-----------------
| element1     | |                |
|   -----------| |-----------     |
|   |element2  \ /          |     |
|   -------------------------     |
|        Event CAPTURING          |
-----------------------------------
</code></pre><p>One thing to note is that, whether you register an event handler in either phase, both phases ALWAYS happen. All events bubble by default. </p>
<p>You can register event handlers for either phase, bubbling or capturing, by using the function <code>addEventListener(type, listener, useCapture)</code>. If <code>useCapture</code> is set to <code>false</code>, the event handler is in the bubbling phase. Otherwise it's in the capture phase. </p>
<p>The order of the phases of the event depends on the browser.</p>
<p>To check which browser honors capture first, you can try the following code in JSfiddle: </p>
<pre><code class="lang-html"><span class="hljs-tag">&lt;<span class="hljs-name">div</span> <span class="hljs-attr">id</span>=<span class="hljs-string">"child-one"</span>&gt;</span>
    <span class="hljs-tag">&lt;<span class="hljs-name">h1</span>&gt;</span>
      Child One
    <span class="hljs-tag">&lt;/<span class="hljs-name">h1</span>&gt;</span>
  <span class="hljs-tag">&lt;/<span class="hljs-name">div</span>&gt;</span>
</code></pre>
<pre><code class="lang-javascript"><span class="hljs-keyword">const</span> childOne = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"child-one"</span>);

<span class="hljs-keyword">const</span> childOneHandler = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Captured on child one'</span>)
}

<span class="hljs-keyword">const</span> childOneHandlerCatch = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Captured on child one in capture phase'</span>)
}

childOne.addEventListener(<span class="hljs-string">"click"</span>, childOneHandler); 
childOne.addEventListener(<span class="hljs-string">"click"</span>, childOneHandlerCatch, <span class="hljs-literal">true</span>);
</code></pre>
<p>In Firefox, Safari, and Chrome, the output is the following:
<img src="https://github.com/shrutikapoor08/blogs/blob/master/JSByte/img/events_capture_order.png?raw=true" alt="Events in capture phase are fired first" width="600" height="400" loading="lazy"> </p>
<h2 id="heading-how-to-listen-to-an-event">How to listen to an event</h2>
<p>There are two ways to listen to an event: </p>
<ol>
<li><code>addEventListener</code> </li>
<li><p>inline events, such as <code>onclick</code></p>
<p>```
//addEventListener
document.getElementByTag('a').addEventListener('click', onClickHandler);</p>
</li>
</ol>
<p>//inline using onclick
<a href="#">Click me</a></p>
<pre><code>
## Which is better - an inline event or <span class="hljs-string">`addEventListener`</span>?

<span class="hljs-number">1.</span> <span class="hljs-string">`addEventListener`</span> gives you the ability to register unlimited event handlers.
<span class="hljs-number">2.</span> <span class="hljs-string">`removeEventListener`</span> can also be used to remove event handlers
<span class="hljs-number">3.</span> The <span class="hljs-string">`useCapture`</span> flag can be used to indicate whether an event needs to be handled <span class="hljs-keyword">in</span> the capture phase or bundled phase.


## Code examples and live-action

You can <span class="hljs-keyword">try</span> out these events <span class="hljs-keyword">in</span> JSFiddle to play around <span class="hljs-keyword">with</span> them. 

<span class="hljs-string">``</span><span class="hljs-string">`html
&lt;div id="wrapper-div"&gt;
  &lt;div id="child-one"&gt;
    &lt;h1&gt;
      Child One
    &lt;/h1&gt;
  &lt;/div&gt;
  &lt;div id="child-two" onclick="childTwoHandler"&gt;
    &lt;h1&gt;
      Child Two
    &lt;/h1&gt;
  &lt;/div&gt;

&lt;/div&gt;</span>
</code></pre><pre><code class="lang-javascript"><span class="hljs-keyword">const</span> wrapperDiv = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"wrapper-div"</span>);
<span class="hljs-keyword">const</span> childOne = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"child-one"</span>);
<span class="hljs-keyword">const</span> childTwo = <span class="hljs-built_in">document</span>.getElementById(<span class="hljs-string">"child-two"</span>);

<span class="hljs-keyword">const</span> childOneHandler = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Captured on child one'</span>)
}

<span class="hljs-keyword">const</span> childTwoHandler = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Captured on child two'</span>)
}

<span class="hljs-keyword">const</span> wrapperDivHandler = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Captured on wrapper div'</span>)
}

<span class="hljs-keyword">const</span> childOneHandlerCatch = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Captured on child one in capture phase'</span>)
}

<span class="hljs-keyword">const</span> childTwoHandlerCatch = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Captured on child two in capture phase'</span>)
}

<span class="hljs-keyword">const</span> wrapperDivHandlerCatch = <span class="hljs-function">() =&gt;</span> {
<span class="hljs-built_in">console</span>.log(<span class="hljs-string">'Captured on wrapper div in capture phase'</span>)
}


childOne.addEventListener(<span class="hljs-string">"click"</span>, childOneHandler); 
childTwo.addEventListener(<span class="hljs-string">"click"</span>, childTwoHandler); 
wrapperDiv.addEventListener(<span class="hljs-string">"click"</span>, wrapperDivHandler); 

childOne.addEventListener(<span class="hljs-string">"click"</span>, childOneHandlerCatch, <span class="hljs-literal">true</span>); 
childTwo.addEventListener(<span class="hljs-string">"click"</span>, childTwoHandlerCatch, <span class="hljs-literal">true</span>); 
wrapperDiv.addEventListener(<span class="hljs-string">"click"</span>, wrapperDivHandlerCatch, <span class="hljs-literal">true</span>);
</code></pre>
<h2 id="heading-tldr">TL;DR</h2>
<p>Event phases are capture (DOM -&gt; target), bubble (target-&gt; DOM) and target. 
Events can be listened for by using <code>addEventListener</code> or inline methods such as <code>onclick</code>. </p>
<pre><code>    addEventListener can add multiple events, whereas <span class="hljs-keyword">with</span> onclick <span class="hljs-built_in">this</span> cannot be done.
    onclick can be added <span class="hljs-keyword">as</span> an HTML attribute, whereas an addEventListener can only be added within &lt;script&gt; elements.
    addEventListener can take a third argument which can stop the event propagation.
</code></pre><h2 id="heading-futher-reading">Futher reading</h2>
<p>https://www.quirksmode.org/js/events_order.html
https://jsfiddle.net/r2bc6axg/
https://stackoverflow.com/questions/6348494/addeventlistener-vs-onclick
https://www.w3.org/wiki/HTML/Attributes/_Global#Event-handler_Attributes</p>
<p>To keep up with more short tutorials like this, <a target="_blank" href="https://tinyletter.com/shrutikapoor">sign up for my newsletter</a> or <a target="_blank" href="https://twitter.com/shrutikapoor08">follow me on Twitter</a></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript Timing Events: setTimeout and setInterval ]]>
                </title>
                <description>
                    <![CDATA[ Programmers use timing events to delay the execution of certain code, or to repeat code at a specific interval. There are two native functions in the JavaScript library used to accomplish these tasks: setTimeout() and setInterval(). setTimeout setTim... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-timing-events-settimeout-and-setinterval/</link>
                <guid isPermaLink="false">66c35923f83dfae169b2bff7</guid>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ toothbrush ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 01 Feb 2020 00:00:00 +0000</pubDate>
                <media:content url="https://cdn-media-2.freecodecamp.org/w1280/5f9c9ce8740569d1a4ca34d2.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>Programmers use timing events to delay the execution of certain code, or to repeat code at a specific interval.</p>
<p>There are two native functions in the JavaScript library used to accomplish these tasks: <code>setTimeout()</code> and <code>setInterval()</code>.</p>
<h3 id="heading-settimeout">setTimeout</h3>
<p><code>setTimeout()</code> is used to delay the execution of the passed function by a specified amount of time.</p>
<p>There are two parameters that you pass to <code>setTimeout()</code>: the function you want to call, and the amount of time in milliseconds to delay the execution of the function.</p>
<p>Remember that there are 1000 milliseconds (ms) in a 1 second, so 5000 ms is equal to 5 seconds.</p>
<p><code>setTimeout()</code> will execute the function from the first argument one time after the specified time has elapsed.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> timeoutID;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delayTimer</span>(<span class="hljs-params"></span>) </span>{
  timeoutID = <span class="hljs-built_in">setTimeout</span>(delayedFunction, <span class="hljs-number">3000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delayedFunction</span>(<span class="hljs-params"></span>) </span>{
  alert(“Three seconds have elapsed.”);
}
</code></pre>
<p>When the <code>delayTimer</code> function is called it will run <code>setTimeout</code>. After 3 seconds (3000 ms) pass, it will execute <code>delayedFunction</code> which will send an alert.</p>
<p><strong>setInterval</strong></p>
<p>Use <code>setInterval()</code> to specify a function to repeat with a time delay between executions. </p>
<p>Again, two parameters are passed to <code>setInterval()</code>: the function you want to call, and the amount of time in milliseconds to delay each call of the function . </p>
<p><code>setInterval()</code> will continue to execute until it is cleared.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> intervalID;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">repeatEverySecond</span>(<span class="hljs-params"></span>) </span>{
  intervalID = <span class="hljs-built_in">setInterval</span>(sendMessage, <span class="hljs-number">1000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">sendMessage</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">console</span>.log(“One second elapsed.”);
}
</code></pre>
<p>When your code calls the function <code>repeatEverySecond</code> it will run <code>setInterval</code>. <code>setInterval</code> will run the function <code>sendMessage</code> every second (1000 ms).</p>
<h3 id="heading-cleartimeout-and-clearinterval">clearTimeout and clearInterval</h3>
<p>There are also corresponding native functions to stop the timing events: <code>clearTimeout()</code> and <code>clearInterval()</code>.</p>
<p>You may have noticed that each timer function above is saved to a variable. When either the <code>setTimeout</code> or <code>setInterval</code> function runs, it is assigned a number which is saved to this variable. Note that JavaScript does this all in the background.</p>
<p>This generated number is unique for each instance of timers. This assigned number is also how timers are identified when you want to stop them. For this reason, you must always set your timer to a variable.</p>
<p>For clarity of your code, you should always match <code>clearTimeout()</code> to <code>setTimeout()</code> and <code>clearInterval()</code> to <code>setInterval()</code>.</p>
<p>To stop a timer, call the corresponding clear function and pass it the timer ID variable that matches the timer you wish to stop. The syntax for <code>clearInterval()</code> and <code>clearTimeout()</code> are the same.</p>
<p><strong>Example:</strong></p>
<pre><code class="lang-javascript"><span class="hljs-keyword">let</span> timeoutID;

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delayTimer</span>(<span class="hljs-params"></span>) </span>{
  timeoutID = <span class="hljs-built_in">setTimeout</span>(delayedFunction, <span class="hljs-number">3000</span>);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">delayedFunction</span>(<span class="hljs-params"></span>) </span>{
  alert(“Three seconds have elapsed.”);
}

<span class="hljs-function"><span class="hljs-keyword">function</span> <span class="hljs-title">clearAlert</span>(<span class="hljs-params"></span>) </span>{
  <span class="hljs-built_in">clearTimeout</span>(timeoutID);
}
</code></pre>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Simplifying an event sourced application ]]>
                </title>
                <description>
                    <![CDATA[ By Bertil Muth Every time you make a change to the application state, you record the change as an event.You can replay the events since the beginning of the recording, up to a  certain time. Then you've recreated the state of the application at that ... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/simplifying-an-event-sourced-application/</link>
                <guid isPermaLink="false">66d45def182810487e0ce119</guid>
                
                    <category>
                        <![CDATA[ coding ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Event Sourcing ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Java ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Fri, 21 Jun 2019 12:43:28 +0000</pubDate>
                <media:content url="https://www.freecodecamp.org/news/content/images/2019/06/EventSourcing.jpg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Bertil Muth</p>
<p>Every time you make a change to the application state, you record the change as an event.<br>You can replay the events since the beginning of the recording, up to a  certain time. Then you've recreated the state of the application at that  time.</p>
<p>That's what <a target="_blank" href="https://martinfowler.com/eaaDev/EventSourcing.html">Event Sourcing</a> is about. It's like you can time travel to the past. I find it fascinating.</p>
<p>Event sourcing provides an audit trail when you need to meet  regulatory requirements. It can help with debugging. And you can even  explore alternate realities: what would have happened if...</p>
<p>I recently saw a <a target="_blank" href="https://youtu.be/r7AGQsM7ncA">great talk</a> by <a target="_blank" href="https://twitter.com/JakubPilimon">Jakub Pilimon</a> and <a target="_blank" href="https://twitter.com/kennybastani">Kenny Bastani</a> about event sourcing.</p>
<p>The talk is a 1 hour session of life coding. The two speakers start with a simple application that is <em>not</em> event sourced. Then they refactor it to use events.</p>
<p>They end up wiring the application up with Apache Kafka. I will skip  that part in this article and focus on the conceptual part of event  sourcing instead.</p>
<h2 id="heading-a-recap-of-the-talk">A recap of the talk</h2>
<p>As a user of a Credit Card management application, you can:</p>
<ul>
<li>Assign a limit to the credit card</li>
<li>Withdraw money</li>
<li>Repay money</li>
</ul>
<p>For each of these commands, there is a method in the <code>CreditCard</code> class.<br>Here's the original code of the <code>assignLimit</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">assignLimit</span><span class="hljs-params">(BigDecimal amount)</span> </span>{ 
  <span class="hljs-keyword">if</span>(limitAlreadyAssigned()) {  
    <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException(); 
  }
  <span class="hljs-keyword">this</span>.initialLimit = amount; 
}
</code></pre>
<p>Here's the <code>withdraw</code> method:</p>
<pre><code class="lang-java">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(BigDecimal amount)</span> </span>{
        <span class="hljs-keyword">if</span>(notEnoughMoneyToWithdraw(amount)) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
        }
        <span class="hljs-keyword">if</span>(tooManyWithdrawalsInCycle()) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
        }
        <span class="hljs-keyword">this</span>.usedLimit = usedLimit.add(amount);
        withdrawals++;
    }
</code></pre>
<p>The <code>repay</code> method is similiar.</p>
<p>Remember that for event sourcing, you need to record an event<br>any time the application changes its state?<br>So the speakers extract each state change to its own method in the <a target="_blank" href="https://gitlab.com/pilloPl/eventsourced-credit-cards/blob/4329a0aac283067f1376b3802e13f5a561f18753/src/main/java/io/pillopl/eventsourcing/model/CreditCard.java">CreditCard</a> class.</p>
<p>Here's the refactored <code>withdraw</code> method:</p>
<pre><code class="lang-java">   <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(BigDecimal amount)</span> </span>{
        <span class="hljs-keyword">if</span>(notEnoughMoneyToWithdraw(amount)) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
        }
        <span class="hljs-keyword">if</span>(tooManyWithdrawalsInCycle()) {
            <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
        }
        cardWithdrawn(<span class="hljs-keyword">new</span> CardWithdrawn(uuid, amount, Instant.now()));
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> CreditCard <span class="hljs-title">cardWithdrawn</span><span class="hljs-params">(CardWithdrawn event)</span> </span>{
        <span class="hljs-keyword">this</span>.usedLimit = usedLimit.add(event.getAmount());
        withdrawals++;
        pendingEvents.add(event);
        <span class="hljs-keyword">return</span> <span class="hljs-keyword">this</span>;
    }
</code></pre>
<p>An instance of <code>CardWithdrawn</code> represents the event that a user has successfully withdrawn money. <em>After</em> the state has changed, the event is added to the list of pending events.</p>
<p>You call the <code>save</code> method of the <a target="_blank" href="https://gitlab.com/pilloPl/eventsourced-credit-cards/blob/4329a0aac283067f1376b3802e13f5a561f18753/src/main/java/io/pillopl/eventsourcing/persistence/CreditCardRepository.java">CreditCardRepository</a> class to flush the pending events to the event stream. Event listeners may handle the events then.</p>
<p>Apart from the payload, each event has its own unique identifier and timestamp. So you can sequence and replay the events later.<br>To replay the events for a specific credit card, the repository calls the <code>recreateFrom</code> method of the <a target="_blank" href="https://gitlab.com/pilloPl/eventsourced-credit-cards/blob/4329a0aac283067f1376b3802e13f5a561f18753/src/main/java/io/pillopl/eventsourcing/model/CreditCard.java">CreditCard</a> class, passing in the id of the card and the events stored for it:</p>
<pre><code class="lang-java">    <span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> CreditCard <span class="hljs-title">recreateFrom</span><span class="hljs-params">(UUID uuid, List&lt;DomainEvent&gt; events)</span> </span>{
        <span class="hljs-keyword">return</span> ofAll(events).foldLeft(<span class="hljs-keyword">new</span> CreditCard(uuid), CreditCard::handle);
    }

    <span class="hljs-function"><span class="hljs-keyword">private</span> CreditCard <span class="hljs-title">handle</span><span class="hljs-params">(DomainEvent event)</span> </span>{
        <span class="hljs-keyword">return</span> Match(event).of(
                Case($(Predicates.instanceOf(LimitAssigned.class)), <span class="hljs-keyword">this</span>::limitAssigned),
                Case($(Predicates.instanceOf(CardWithdrawn.class)), <span class="hljs-keyword">this</span>::cardWithdrawn),
                Case($(Predicates.instanceOf(CardRepaid.class)), <span class="hljs-keyword">this</span>::cardRepaid),
                Case($(Predicates.instanceOf(CycleClosed.class)), <span class="hljs-keyword">this</span>::cycleWasClosed)
        );
    }
</code></pre>
<p>This code uses the <a target="_blank" href="http://www.vavr.io/">vavr.io</a> library to call the <code>handle</code> method for each event. The <code>handle</code> method dispatches the event object to the appropriate method.<br>For example: for each <code>LimitAssigned</code> event, the <code>handle</code> method calls the <code>limitAssigned</code> method with the event as parameter.</p>
<h2 id="heading-simplifying-the-application">Simplifying the application</h2>
<p>I used the <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">requirements as code</a> library for simplifying the code. First, I put all of the event classes and the handling methods in a model. Like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">this</span>.eventHandlingModel = 
        Model.builder()
           .on(LimitAssigned.class).system(<span class="hljs-keyword">this</span>::limitAssigned)
           .on(CardWithdrawn.class).system(<span class="hljs-keyword">this</span>::cardWithdrawn)
           .on(CardRepaid.class).system(<span class="hljs-keyword">this</span>::cardRepaid)
           .on(CycleClosed.class).system(<span class="hljs-keyword">this</span>::cycleWasClosed)
       .build();
</code></pre>
<p>I had to change the return type of the handling methods (e.g. <code>limitAssigned</code>) to <code>void</code>. Apart from that, the conversion from <a target="_blank" href="http://www.vavr.io/">vavr.io</a> was straight forward.</p>
<p>Then, I created a runner and started it for the model:</p>
<pre><code class="lang-java"><span class="hljs-keyword">this</span>.modelRunner = <span class="hljs-keyword">new</span> ModelRunner();
modelRunner.run(eventHandlingModel);
</code></pre>
<p>After that, I changed the <code>recreateFrom</code> and <code>handle</code> methods to this:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">static</span> CreditCard <span class="hljs-title">recreateFrom</span><span class="hljs-params">(UUID uuid, List&lt;DomainEvent&gt; events)</span> </span>{
    CreditCard creditCard = <span class="hljs-keyword">new</span> CreditCard(uuid);
    events.forEach(ev -&gt; creditCard.handle(ev));
    <span class="hljs-keyword">return</span> creditCard;
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">handle</span><span class="hljs-params">(DomainEvent event)</span> </span>{
    modelRunner.reactTo(event);
}
</code></pre>
<p>At that point, I could get rid of the dependency to <a target="_blank" href="http://www.vavr.io/">vavr.io</a>.<br>Transition complete. Now I could get some more simplifying done.</p>
<p>I revisited the <code>withdraw</code> method:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(BigDecimal amount)</span> </span>{
    <span class="hljs-keyword">if</span>(notEnoughMoneyToWithdraw(amount)) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
    }
    <span class="hljs-keyword">if</span>(tooManyWithdrawalsInCycle()) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
    }
    cardWithdrawn(<span class="hljs-keyword">new</span> CardWithdrawn(uuid, amount, Instant.now()));
}
</code></pre>
<p>The check <code>tooManyWithdrawalsInCycle()</code> didn't depend on the data of the event. It only depended on the state of the <code>CreditCard</code>.<br>State checks like this can be represented in the model as <code>conditions</code>.</p>
<p>After I moved all state checks for all methods to the model, it looked like this:</p>
<pre><code class="lang-java"><span class="hljs-keyword">this</span>.eventHandlingModel = 
  Model.builder()
    .condition(<span class="hljs-keyword">this</span>::limitNotAssigned)
        .on(LimitAssigned.class).system(<span class="hljs-keyword">this</span>::limitAssigned)
    .condition(<span class="hljs-keyword">this</span>::limitAlreadyAssigned)
        .on(LimitAssigned.class).system(<span class="hljs-keyword">this</span>::throwsException)
    .condition(<span class="hljs-keyword">this</span>::notTooManyWithdrawalsInCycle)
        .on(CardWithdrawn.class).system(<span class="hljs-keyword">this</span>::cardWithdrawn)
    .condition(<span class="hljs-keyword">this</span>::tooManyWithdrawalsInCycle)
        .on(CardWithdrawn.class).system(<span class="hljs-keyword">this</span>::throwsException)
    .on(CardRepaid.class).system(<span class="hljs-keyword">this</span>::cardRepaid)
    .on(CycleClosed.class).system(<span class="hljs-keyword">this</span>::cycleWasClosed)
.build();
</code></pre>
<p>For this to work, I needed to replace the direct calls to methods that change the state with the <code>handle</code> method. After that, the <code>assignLimit</code> and <code>withdraw</code> methods looked like this:</p>
<pre><code class="lang-java"><span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">assignLimit</span><span class="hljs-params">(BigDecimal amount)</span> </span>{ 
    handle(<span class="hljs-keyword">new</span> LimitAssigned(uuid, amount, Instant.now()));
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">limitAssigned</span><span class="hljs-params">(LimitAssigned event)</span> </span>{
    <span class="hljs-keyword">this</span>.initialLimit = event.getAmount(); 
    pendingEvents.add(event);
}

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">withdraw</span><span class="hljs-params">(BigDecimal amount)</span> </span>{
    <span class="hljs-keyword">if</span>(notEnoughMoneyToWithdraw(amount)) {
        <span class="hljs-keyword">throw</span> <span class="hljs-keyword">new</span> IllegalStateException();
    }
    handle(<span class="hljs-keyword">new</span> CardWithdrawn(uuid, amount, Instant.now()));
}

<span class="hljs-function"><span class="hljs-keyword">private</span> <span class="hljs-keyword">void</span> <span class="hljs-title">cardWithdrawn</span><span class="hljs-params">(CardWithdrawn event)</span> </span>{
    <span class="hljs-keyword">this</span>.usedLimit = usedLimit.add(event.getAmount());
    withdrawals++;
    pendingEvents.add(event);
}
</code></pre>
<p>As you can see, most of the conditional logic has moved out of the  methods into the model. This makes the methods easier to understand.</p>
<p>One thing that bothered me is that you must not forget to add the  event to the pending events. Every time. Or your code won't work.</p>
<p><a target="_blank" href="https://github.com/bertilmuth/requirementsascode">Requirements as code</a> allows you to control how the system handles the events. So I extracted <code>pendingEvents.add(event)</code> from the methods as well:</p>
<pre><code class="lang-java">modelRunner.handleWith(<span class="hljs-keyword">this</span>::addingPendingEvents);
...

<span class="hljs-function"><span class="hljs-keyword">public</span> <span class="hljs-keyword">void</span> <span class="hljs-title">addingPendingEvents</span><span class="hljs-params">(StepToBeRun stepToBeRun)</span> </span>{
    stepToBeRun.run();
    DomainEvent domainEvent = (DomainEvent) stepToBeRun.getEvent().get();
    pendingEvents.add(domainEvent);
}
</code></pre>
<p>I could have gone further and extract the validation logic as well.<br>But I leave that as a thought exercise to you, dear reader.</p>
<h2 id="heading-whats-the-point">What's the point?</h2>
<p>What I tried to achieve is a clear separation of concerns:</p>
<ul>
<li>The state dependent execution of methods is defined in the model</li>
<li>The data validation and state changes are in the implementations of the methods</li>
<li>The events are automatically added to the pending events. In  general: the infrastructure code is clearly separated from the business  logic.</li>
</ul>
<p>Simplifying an example that is already very simple is good for explaining.<br>But that's not the point I want to make.</p>
<p>The point is: having such a clear separation of concerns pays out in practice.<br>Especially, if you work with multiple teams. On complicated problems.</p>
<p>Separation of concerns helps with changing different parts of code at  a different pace. You have simple rules where to find something. The  code is easier to understand. And it's easier to isolate units for  testing purposes.</p>
<h2 id="heading-conclusion">Conclusion</h2>
<p>I hope you enjoyed my article. Please give me feedback.</p>
<p>Have you been working on event sourcing applications?<br>What were your experiences like?<br>Can you relate to what I wrote in this article?</p>
<p>I also want to invite you to look at <a target="_blank" href="https://github.com/bertilmuth/requirementsascode">my library</a> that I used throughout the article. I would be thrilled if you try it out in practice, and tell me what you think.</p>
<p><em>This article was first published on <a target="_blank" href="https://dev.to/bertilmuth/simplifying-an-event-sourced-application-1klp">dev.to</a></em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How to Grow (and Save) Your Favorite Tech Meetup ]]>
                </title>
                <description>
                    <![CDATA[ By Jen Weber Hey meetup facilitators, friends, and future leaders! Do you want more people to show up to your tech event? Or at least the same number of people? Here are some ideas to try! These tips are based on observations of Boston’s meetup cultu... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/five-tips-for-growing-your-tech-meetup-4c39c0ab3f78/</link>
                <guid isPermaLink="false">66c34a874f7405e6476b01ae</guid>
                
                    <category>
                        <![CDATA[ Ember.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Meetup ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Mon, 05 Feb 2018 13:10:54 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*PU2hT6eCDwxw8dHrMRcX-g.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Jen Weber</p>
<p>Hey meetup facilitators, friends, and future leaders! Do you want more people to show up to your tech event? Or at least the same number of people? Here are some ideas to try! These tips are based on observations of Boston’s meetup culture and my experience running a group focused on <a target="_blank" href="https://emberjs.com/">Ember.js</a> (a front-end framework).</p>
<h3 id="heading-1-dont-just-ask-for-new-speakers-create-them">1. Don’t just ask for new speakers — create them</h3>
<p>While Boston Ember is pretty steady, I’ve seen other meetups struggle to find speakers. As a facilitator, it’s my responsibility to curate a variety of talks, both by topic and experience level. To achieve that, I wanted to help bring in new speakers. I needed an enormous amount of cajoling to give my first tech talk, and I can’t cajole attendees at scale, so what can be done?</p>
<p>First, make an event of it! Find an experienced speaker who will answer public speaking questions. You could also assemble a panel. Check out the results of our attempt <a target="_blank" href="https://youtu.be/ZZRz3fRShDw?t=3078">here</a>, as presented by <a target="_blank" href="https://github.com/srvance">Stephen Vance</a>. The audience was 100% captivated.</p>
<p>He asked the attendees which category of information they were most interested in:</p>
<ul>
<li>choosing topics</li>
<li>preparation</li>
<li>delivery</li>
<li>follow on (handling audience questions)</li>
<li>remote presenting.</li>
</ul>
<p>Then, based on audience vote for the focus, Stephen took Q&amp;A for the most popular categories.</p>
<p>Second, follow up. Set aside a slot for a new speaker. Advertise it that way. Many potential speakers may believe that they need to be “experts” or that someone else is more worthy. Help them overcome imposter syndrome by extending an invitation.</p>
<h3 id="heading-2-avoid-lengthy-product-pitch-talks">2. Avoid lengthy product pitch talks</h3>
<p>Product pitches kill tech meetups. If you don’t take steps to cultivate new speakers, your only volunteers may be people who have something to sell. Your devs will get bored of sales pitches, and they’ll stop showing up.</p>
<p>Here’s the litmus test for whether it’s a product pitch. Ask the potential presenter,”What will the audience take away from the talk? What will you teach them?” If it’s teaching about a business use case, the company, the industry and so on, offer them a spot for a lightning talk, ten minutes or less.</p>
<p>I was a salesperson before I became a developer, and I can empathize with the product pitch speakers. But be firm. You owe it to your attendees. If the speaker shares more than a product pitch, you can invite them to speak again for a longer time slot.</p>
<h3 id="heading-3-run-a-raffle-at-the-end">3. Run a raffle at the end</h3>
<p>Every month, I go to <a target="_blank" href="https://www.shegeeksout.com/">She Geeks Out</a>, an amazing event run by some women who are real pros at community engagement. Every month, they do a raffle at the end of the evening, and the energy it brings to the room is incredible. People stay until the end, they cheer each other on, and no speaker is ever confronted with “So, I guess that’s it for questions. Bye, have a good night.” Instead, it’s “Who’s ready to win tonight!?!? It’s raffle time.”</p>
<p>At the end of the day, our animal brains love the chance to win a prize.</p>
<p>So, I tried this out for one of our special events, using some Ember swag. Because I’m a nerd, I printed out some Ember API methods and wrote a <a target="_blank" href="https://repl.it/@jwwweber/RaffleTime">script to select them at random</a>. Even the people who were already <strong>wearing</strong> some swag were intent on winning.</p>
<p>You don’t have to spend a ton of money either to add some magic to your event. Think of it as the cost of pizza for just one more attendee. Buy $40 of <a target="_blank" href="http://www.thinkgeek.com/clearance/on-sale/price/asc/0/300/">clearance stuff from ThinkGeek</a> and you’re good to go for the year.</p>
<h3 id="heading-4-be-in-cahoots-with-other-meetups">4. Be in cahoots with other meetups</h3>
<p>In 2017, the Boston tech meetup scene suffered some serious blows. Many popular groups went poof, and seemingly the number of venues willing to host tanked. To form a support network, some local meetup organizers created Boston JavaScript. It is a <a target="_blank" href="https://boston-javascript-slackin.herokuapp.com">Slack organization</a> where local groups could share and grow together. Then, they invited every group and their organizers to join.</p>
<p>It’s important for developers to consider tools outside their wheelhouse. We all have a lot to learn from each other! The shared space enables us to share event announcements and collaborate.</p>
<p>I also reached out to some people in my Ember network to ask for advice. I spoke with other local members, past leaders, and facilitators in other states. They shared ideas I had never seen in action before.</p>
<h3 id="heading-5-every-month-take-action-to-build-sustainability">5. Every month, take action to build sustainability</h3>
<p>So what killed the Boston meetups in 2017? My guess is that the organizers needed a break, which is natural, but no one else was ready to take over.</p>
<p>It’s important to take steps <strong>today</strong> to prepare for when you and your partners will inevitably be moving on to something else. Don’t wait until that time hits.</p>
<p>I’m still exploring this myself, but here’s what I’ve gathered from other meetup leaders:</p>
<ul>
<li>Ask for help, even when you don’t need it. Your helpers will become the future leaders.</li>
<li>Form a coalition. I recently heard of a meetup run by 6 people. It is very stable.</li>
<li>Suggest many ways to help. Social media, livestream, and event advertising are all good ways for people to pitch in. Volunteers don’t need to be comfortable in front of a crowd.</li>
<li>Let go of some control. Share responsibilities with your co-facilitators. Accept that they will do things differently than you would.</li>
<li>Rotate the emcee, at least for certain sections of the event. People besides you need practice before they’d ever agree to be a copilot or take over facilitation.</li>
<li>Get the attendees involved as <strong>participants</strong>. Ask them to be speakers and ask them for feedback. Have a session where people can propose topics they’re interested in hearing about. If people show up and leave without contributing, you may become the only one who cares enough to put in the work. <strong>Make it everyone’s baby</strong>.</li>
</ul>
<h3 id="heading-in-closing">In closing…</h3>
<p>When I first stepped up to help run a meetup, I was terribly worried. I was afraid that no one would show up, that I wouldn’t be able to find venues/sponsors, that people would stop coming… that I wasn’t good enough. I got on the phone with the facilitator of the <a target="_blank" href="https://www.meetup.com/EmberJS-NYC/">NYC Ember.js</a>, <a target="_blank" href="https://mobile.twitter.com/lukemelia">Luke Melia</a>, and I asked him a thousand anxiety-fueled questions.</p>
<p>He said something like this:</p>
<blockquote>
<p>Before I answer any of these questions, I want to make one point. You are going to have so much fun! Running a meetup is an incredibly valuable experience. You will learn <strong>so much</strong>.</p>
</blockquote>
<p>He was right.</p>
<p>Jen Weber builds apps for science at <a target="_blank" href="https://biobright.com/">BioBright</a>. She’s a contributor to <a target="_blank" href="https://emberjs.com/">Ember.js</a>, a front end framework that comes with “batteries included” for better developer experience and productivity. She works to transform tech into an industry that welcomes new people.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ How Conference Speakers Get Compensated ]]>
                </title>
                <description>
                    <![CDATA[ By Ovid In dealing with a flurry of recent emails regarding compensating speakers for events, I realized that more people should be aware of how speaker compensation is handled, particularly if you want to organize an event. That being said, it’s a r... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/how-conference-speakers-get-compensated-93b49fd370f1/</link>
                <guid isPermaLink="false">66c34ce8a7aea9fc97bdfb60</guid>
                
                    <category>
                        <![CDATA[ conference ]]>
                    </category>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ startup ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                    <category>
                        <![CDATA[ technology ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Tue, 13 Jun 2017 07:04:20 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*e5flIoQf_jfcYYoSD0MkyA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Ovid</p>
<p>In dealing with a flurry of recent emails regarding compensating speakers for events, I realized that more people should be aware of how speaker compensation is handled, particularly if you want to organize an event.</p>
<p>That being said, it’s a rather touchy topic so I’ll try to tread lightly. And I’ll mainly be talking about typical non-corporate software conferences. I also speak at private/corporate events across Europe and the US and they’re a different ball game.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/7xoKPE0mmEl47iA3K4LEve-pxGpffVcaVGWn" alt="Image" width="800" height="533" loading="lazy">
_Me after giving a talk in Lisbon, Portugal. The cocky air was probably unintentional. [Photo by Rafael Garcia-Suarez](https://www.flickr.com/photos/rgarciasuarez74/3794820418" rel="noopener" target="<em>blank" title=")</em></p>
<h3 id="heading-the-different-types-of-speakers"><strong>The Different Types of Speakers</strong></h3>
<p>At a conference, attendees fall into several groups, but I’ll just cover regular and invited (guest) speakers.</p>
<p>A regular speaker is typically someone’s who’s submitted a talk for a conference and gotten it accepted. While the compensation varies, the only standard is a waiving of the attendance fee. Other forms of compensation may be a speaker’s dinner, “speaker only” swag, or other perks such as the <a target="_blank" href="http://jceventphoto.com/oscon_2013.html">professional photographer work you see at OSCON</a>.</p>
<p>A regular speaker <em>might</em> have pitched a tutorial and those people often get part (or all) of the tutorial money and <em>might</em> have their travel and hotel covered. This bit seems more “hit or miss” depending on the conference. That being said, <a target="_blank" href="https://allaroundtheworld.fr/training">my company’s training courses</a> are typically in a corporate environment and I don’t have much to say about conference training.</p>
<p>Then you have the invited, or “guest” speakers. These are the speakers that a conference uses to promote themselves. Not only does the conference offer a wide array of interesting topics and a chance to network with other people in your field, strong guest speakers such as <a target="_blank" href="http://www.antipope.org/charlie/blog-static/2014/06/yapcna-2014-keynote-programmin.html">Charles Stross</a> are a powerful draw. Or if you’ve ever seen <a target="_blank" href="http://www.oscon.com/oscon2014/public/schedule/speaker/4710">Damian Conway</a> speak, you <em>know</em> why people want to go see him. <a target="_blank" href="https://medium.com/yapc-europe-2016/yapc-europe-2016-speakers-curtis-ovid-poe-afad470a08fa">I’ve also been fortunate enough to be featured as a keynote speaker at conferences</a>.</p>
<h3 id="heading-guest-speakers"><strong>Guest Speakers</strong></h3>
<p>As mentioned, I’m often invited to speak at conferences, such as giving the <a target="_blank" href="http://act.yapc.eu/ye2014/talk/5669">Day 1 Keynote at a conference in Bulgaria</a>. I certainly don’t claim to have the appeal of Damian Conway or Charles Stross (though with a rating of <a target="_blank" href="http://www.oscon.com/oscon2014/public/schedule/detail/33557">5 out of 5 stars for my last US OSCON talk</a>, I’m not too shabby), but nonetheless I have given a number of keynotes, or have been invited to just be a “special guest.” When you’re invited to a conference, that’s when things change a bit.</p>
<p>If I go to all of the events I’m invited to, I’d hardly see my family and <a target="_blank" href="https://allaroundtheworld.fr/">my business</a> would suffer; I <em>can’t</em> attend every event I’m invited to. Rachel Nabors, on a recent podcast where she discussed how <a target="_blank" href="http://ladiesintech.com/podcast-rachel-nabors/">speaking can help or hurt your business</a>, stated that she loses on average $3,000 for every conference she attends. I find that’s actually on the low side if you count all the prep time for a great talk and how many days I’ll be away (my travel’s particularly painful as I live in a small town on the southwest coast of France with no airport).</p>
<p>As for myself, I often speak at Perl events and in the previously mentioned email thread, someone claimed that, with a couple of exceptions, invited speakers to non-corporate software conferences do not receive compensation for these events. This is a misunderstanding. Invited speakers to said events often do not receive <em>speaking fees</em>.</p>
<p><a target="_blank" href="http://www.oreillynet.com/pub/a/social-media/excerpts/9780596802004/why-speakers-earn-30k-an-hour.html">Top public speakers can earn very good money</a>, but for these conferences, not so much. And just to be crystal clear: <strong>I have never asked for a speaking fee for a Perl event</strong>. The Perl community has given me a lot and I try to give back in return. It also helps that I’ve a lot of friends there. If a Perl event wants to <em>offer</em> me a speaking fee and I think it won’t hurt them, I’ll accept, but I have never made that a precondition of my speaking.</p>
<p>When I speak at other conferences/events, I decide on a case-by-case basis. For a quick pep talk or a new take on a talk I’ve previously given, it’s pretty easy. If I’m asked to write something tailored for a given event, that changes the whole game plan.</p>
<p>People who don’t do public speaking often don’t get how labor intensive it is. If I’m giving a talk on strategic agile business practices, designing OO systems, or database design, or even “how to move to a foreign country,” there’s a huge amount of research involved and if I don’t get it right, the audience will eat me alive. And after I get it right, I have to make it both interesting and <em>fun</em>. Oh, and fit it into whatever time slot is available. That’s hard work, even if I’m only giving a motivational talk.</p>
<p>However, as previously mentioned, short of me deciding I want to make a full time living as a public speaker, there are only so many events I can afford to attend before I start hurting my business (and as mentioned, this isn’t just about lost income). That’s why when I am invited to a conference, I ask for travel and accommodation to offset the costs. And when I say “accommodation”, I’m happy to kip in someone’s spare bedroom. I am well aware that many conferences are run on shoestring budgets and I have no desire to break them.</p>
<p>Instead, I view these events as marketing and for whatever costs I incur, my company budgets them as such. The benefit of marketing outweighs the cost of the conference itself, so long as one’s careful about the conferences attended.</p>
<h3 id="heading-some-advice-for-conference-organizers"><strong>Some Advice for Conference Organizers</strong></h3>
<p>A smart conference will arrange the speaker’s flight and hotel themselves rather than leave it up to the speaker. Yes, it’s more work for you to arrange all of this in advance, but there are a handful of speakers who have hurt conferences with 4 star hotels and business class flights whose costs the conference wasn’t expecting to cover.</p>
<p>The speaker may not even have realized they were causing a problem, but nonetheless, it does happen and can make the difference in whether or not the conference can cover all of their debts. For private events, we’ve pretty much stopped billing flight and hotel separately (unless asked) because so many businesses have also been bitten by this.</p>
<p>It’s also interesting to note the number of requests for new talks. For new talks, we don’t just slap together a slide deck at the last minute. We spend a huge amount of time writing the material, practicing it, working on our timing, cutting slides, writing new slides, cursing when we realize we have to cut our favorite joke, and so on. Watch my <a target="_blank" href="https://www.youtube.com/watch?v=kKOqOMqp7wQ">Agile Companies Go POP</a> talk in Kiev and you’ll get a sense of how much work is involved.</p>
<p>Even if the speaker has already given a talk, no talk is ever given twice: we react to our audience, we update our material and we stress different points in our presentation. Even if the talk has been posted online, few people watch those all the way to the end. So if you invite us but you can’t afford to pay us, that’s often OK, but be aware that getting a brand-spanking new talk out of it is a bonus.</p>
<h3 id="heading-in-summary"><strong>In Summary</strong></h3>
<p>For most conferences, the majority of speakers only get the conference fee waived and maybe some special swag. For smaller, non-profit conferences, guest speakers are often not paid, but their travel and accommodation expenses are usually covered. For larger conferences and corporate events, guest speakers often receive a speaking fee and the amount varies from event to event, and from speaker to speaker.</p>
<p>Smaller conferences usually only offer speaking fees to a handful of luminaries because that’s all the conference can typically afford. People giving tutorials often get part of the tutorial fees as compensation (OSCON offers a paltry $500 honorarium).</p>
<p>Some well-known personalities at these conferences do not charge speaking fees, but some are in such high demand that they need said fees to offset losses from their main business.</p>
<p><a target="_blank" href="https://www.linkedin.com/pulse/20140731092421-4973136-how-do-conference-speakers-get-compensated"><em>This is an update from a popular LinkedIn post</em></a><em>.</em></p>
<p><em>Curtis “Ovid” Poe is a regular guest speaker at public and private events in Europe and the US. If you’d like him to speak at an event, please sent an inquiry to info at allaroundtheworld dot fr.</em></p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ JavaScript conferences you can look forward to in 2017 ]]>
                </title>
                <description>
                    <![CDATA[ By Dheeraj Joshi Conferences are a great way to make friends and learn from experts. You can even try your hand at presenting on a topic. Here are some JavaScript conferences to look forward to in 2017. NodeConf Budapest: January 19–20 in Budapest, H... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/javascript-conferences-to-attend-in-2017-b46b288a5df0/</link>
                <guid isPermaLink="false">66c358ded372f14b49bdcbbc</guid>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ JavaScript ]]>
                    </category>
                
                    <category>
                        <![CDATA[ React ]]>
                    </category>
                
                    <category>
                        <![CDATA[ startup ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Wed, 28 Dec 2016 15:09:11 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*y7O_letkTacy1IxtZkmpCA.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Dheeraj Joshi</p>
<p>Conferences are a great way to make friends and learn from experts. You can even try your hand at presenting on a topic.</p>
<p>Here are some JavaScript conferences to look forward to in 2017.</p>
<h4 id="heading-nodeconf-budapest-january-1920-in-budapest-hungary">NodeConf Budapest: January 19–20 in Budapest, Hungary</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/jJOyStYFuSnOUdpznSzUDAW4yp5N55V4LTAG" alt="Image" width="800" height="374" loading="lazy"></p>
<p><a target="_blank" href="https://nodeconf.risingstack.com/">NodeConf Budapest</a> is a one-day, single-track conference with a laser focus on what people need to know about Node.js. There’s also a special NodeSchool event the day before.</p>
<h4 id="heading-agent-conference-january-2021-in-dornbirn-austria">Agent Conference: January 20–21 in Dornbirn, Austria</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/SUjgBHA4lIDfgqALbh2X06PPlS5p2aaGkz8i" alt="Image" width="114" height="114" loading="lazy"></p>
<p><a target="_blank" href="http://www.agent.sh/">AgentConf</a> is the first alpine conference about JavaScript and software engineering. Experts and core contributors will come to showcase their work in ReactJS, ReactNative, Node, and more.</p>
<h4 id="heading-script17-january-27-in-linz-austria">Script’17: January 27 in Linz, Austria</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/b-uO0HBO28UZYHK1jwwvfXpsDLdeaXAsqDCr" alt="Image" width="796" height="175" loading="lazy"></p>
<p><a target="_blank" href="https://scriptconf.org/">Script’17</a> is a one-day event focused on JavaScript.</p>
<h4 id="heading-developer-week-february-1315-in-san-francisco-california">Developer Week: February 13–15 in San Francisco, California</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/IGjaRIBZEgf1Mq9Q1Dn14zziCu2SHu9BpSIC" alt="Image" width="678" height="507" loading="lazy"></p>
<p>This is the first time that <a target="_blank" href="http://www.developerweek.com/javascript-conference/">DeveloperWeek</a> will feature a JavaScript conference. It’s 3-days of workshops and industry talks about JavaScript.</p>
<h4 id="heading-react-london-march-28-in-london-uk">React London: March 28 in London, UK</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/rcNFqLiMpw2iQ02msTd5k6WfRcQQeKgqLGQ2" alt="Image" width="120" height="120" loading="lazy"></p>
<p>Red Badger is launching a new conference focused on React in London for 2017 called <a target="_blank" href="https://react.london/">React London 2017</a>.</p>
<h4 id="heading-emberconf-march-2829-in-portland-oregon">EmberConf: March 28–29 in Portland, Oregon</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/l65YmBva1yM9LU4tZxeUzEGW8Oj8Www-PEg0" alt="Image" width="310" height="163" loading="lazy"></p>
<p><a target="_blank" href="http://emberconf.com/">EmberConf</a> features sessions, activities, and good times with the Ember Core Team and community members from around the world.</p>
<h4 id="heading-render-march-3031-in-oxford-uk">Render: March 30–31 in Oxford, UK</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/p3jL1BpTBV6kfL9Ng2BjzHVvjHv7qrOFTe2X" alt="Image" width="300" height="300" loading="lazy"></p>
<p><a target="_blank" href="http://2017.render-conf.com//">Render Conf</a> is a 2-day conference for front-end developers. It’s the successor to <a target="_blank" href="https://medium.com/@whiteoctevents/life-after-jquery-uk-5253277d556c#.9dtjtzs7j">jQuery UK</a>, returning to Oxford for its second year in 2017. It’s a single-track conference.</p>
<h4 id="heading-smashingconf-april-45-in-san-francisco-california">SmashingConf: April 4–5 in San Francisco, California</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/HTzLkeWNyedCipYFPxU8vKr2qc4DC9sOd4ZA" alt="Image" width="300" height="81" loading="lazy"></p>
<p><a target="_blank" href="https://smashingconf.com/">SmashingConf</a> features focuses on UX and front end development.</p>
<h4 id="heading-ng-conf-april-57-in-salt-lake-city-utah">ng-conf: April 5–7 in Salt Lake City, Utah</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/4m5XnAFafhWpXVK-MtQa3xjFGl8DOy5hKyAq" alt="Image" width="280" height="308" loading="lazy"></p>
<p><a target="_blank" href="https://www.ng-conf.org/">ng-conf</a> is the world’s original Angular Conference.</p>
<h4 id="heading-react-amsterdam-april-21-in-amsterdam-the-netherlands">React Amsterdam: April 21 in Amsterdam, The Netherlands</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/rGVVG8Uz--DV2Xp1M2K3TAx1Lf7WtCIgSuww" alt="Image" width="180" height="180" loading="lazy"></p>
<p><a target="_blank" href="https://react.amsterdam/">React Amsterdam</a> is a full day two-track conference on all things React.</p>
<h4 id="heading-active-ingredients-april-28-in-san-francisco-california">Active Ingredients: April 28 in San Francisco, California</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/4M92Dth5rsHT9CITiKa3jRtnGLnyRo08WnOO" alt="Image" width="749" height="126" loading="lazy"></p>
<p><a target="_blank" href="https://activeingredients.info/">Active Ingredients 2017</a> is the world’s first conference that is focusing on JAMstack. Spend a day learning from some of the most prominent people in web development.</p>
<h4 id="heading-jsconf-eu-may-67-in-berlin-germany">JSConf EU: May 6–7 in Berlin, Germany</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/p-HeznwCS6kE3fbe1V9gOK3xHRF2-JAi7LEX" alt="Image" width="200" height="200" loading="lazy"></p>
<p><a target="_blank" href="http://2017.jsconf.eu/">JSConf EU</a> is the labor-of-love conference for the JavaScript community in Europe.</p>
<h4 id="heading-jsday-italy-may-1011-in-verona-italy">JSDay Italy: May 10–11 in Verona, Italy</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/J0qlyBPB4foTRuCKW7Yke10THcRqhR-EmGvW" alt="Image" width="414" height="164" loading="lazy"></p>
<p>From the organizers of the phpDay, <a target="_blank" href="http://2017.jsday.it/">JSDay</a> is the first international conference on JavaScript in Italy.</p>
<h4 id="heading-react-europe-may-1819-in-paris-france">React Europe: May 18–19 in Paris, France</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/LNBECKSbEDA-qLEu5Oxld84CYVnJEtBL-xBk" alt="Image" width="300" height="300" loading="lazy"></p>
<p><a target="_blank" href="https://www.react-europe.org/">ReactEurope</a> will explore new ways to use tools like React.js, React Native, GraphQL, Relay, Universal apps, Webpack, inline CSS, and more.</p>
<h4 id="heading-front-trends-may-2426-warsaw-poland">Front-Trends, May 24–26, Warsaw, Poland</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/mqOn-alcHX2y5YceoBAineHJd4ZJV8CjFD5e" alt="Image" width="204" height="205" loading="lazy"></p>
<p><a target="_blank" href="https://2017.front-trends.com/">Front-Trends</a> focuses on front-end development.</p>
<h4 id="heading-ng-cruise-may-29-june-2-in-miami-florida">ng-cruise: May 29-June 2 in Miami, Florida</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/fseSUZtNpRBeGNsJdpxtZPU8sS9-90XmqOMq" alt="Image" width="187" height="147" loading="lazy"></p>
<p>The first <a target="_blank" href="https://ngcruise.com/">Angular cruise</a> conference. The cruise departs from Miami and heads to the Bahamas.</p>
<h4 id="heading-fluent-june-1922-in-san-jose-california">Fluent: June 19–22 in San Jose, California</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/wFzZPgX2HYL5cGqFY6XphEBSFRIG6eewArU1" alt="Image" width="283" height="76" loading="lazy"></p>
<p><a target="_blank" href="http://conferences.oreilly.com/fluent/fl-ca">O’Reilly Fluent</a> will focus on the web development and more.</p>
<h4 id="heading-vueconf-june-2123-in-wroclaw-poland">VueConf: June 21–23 in WROCŁAW, POLAND</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/usmREpVkSFEqLW-e1r5wpqD76q-GYzLaFDqy" alt="Image" width="323" height="156" loading="lazy"></p>
<p><a target="_blank" href="https://conf.vuejs.org/">VueConf</a> is the first Official Vue.js Conference in the world.</p>
<h4 id="heading-angularcamp-july-in-barcelona-spain">AngularCamp: July in Barcelona, Spain</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/AgSprtuifV9dSQu8K0MwyestRUkExhAt--qh" alt="Image" width="225" height="225" loading="lazy"></p>
<p><a target="_blank" href="https://angularcamp.org/">AngularCamp</a> Conference is a one-day, single track conference with amazing talks by internationally renowned community speakers.</p>
<h4 id="heading-frontend-conference-august-31-september-1-in-zurich-switzerland">Frontend Conference: August 31-September 1 in Zurich, Switzerland</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/5jroWtlPmNn5ovinv4PKrqXKDiZh48oVQOMu" alt="Image" width="200" height="200" loading="lazy"></p>
<p>The <a target="_blank" href="https://frontendconf.ch/">Frontend Conference</a> in Zurich is Switzerland’s conference on front-end and UX techniques.</p>
<h4 id="heading-nordicjs-september-78-in-stockholm-sweden">NordicJS: September 7–8 in Stockholm, Sweden</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/xwgwSziJHdtE5KLjWzJohgPCwgyOZVn7gfkX" alt="Image" width="200" height="200" loading="lazy"></p>
<p><a target="_blank" href="http://nordicjs.com/">Nordic.js</a> is a two-day JavaScript conference.</p>
<h4 id="heading-angularconnect-november-78-in-london-uk">AngularConnect: November 7–8 in London, UK</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ehT2YGKSBN4jNz7CAyzHF-VIIuw25sFrUfqA" alt="Image" width="459" height="200" loading="lazy"></p>
<p><a target="_blank" href="http://angularconnect.com/">AngularConnect</a> is a 2-day, multi-track conference with a variety of Angular expercts, including the core Angular team at Google.</p>
<h4 id="heading-halfstack-2017-nov-17-in-london-uk">HalfStack 2017: Nov 17 in London, UK</h4>
<p><img src="https://cdn-media-1.freecodecamp.org/images/yS1sFtyFwfjCJLY8kINd2OWw-pp56g5xSJ2g" alt="Image" width="549" height="160" loading="lazy"></p>
<p><a target="_blank" href="http://halfstackconf.com/">HalfStack</a> is a one-day, single track JavaScript conference that actually takes place in a pub.</p>
<p>Recently, I’ve had a few opportunities to attend and speak at amazing conferences on JavaScript Security. You can <a target="_blank" href="http://engineering.wingify.com/posts/wingify-at-europe-uk-conferences/">read about my experiences</a> and <a target="_blank" href="https://twitter.com/dheerajhere">follow me on Twitter</a>.</p>
 ]]>
                </content:encoded>
            </item>
        
            <item>
                <title>
                    <![CDATA[ Waking up a sleeping city with JavaScript ]]>
                </title>
                <description>
                    <![CDATA[ By Koustuv Sinha Not once, but twice, our college became a part of an International community of highly productive and engaging people. The most recent installment took place on last Saturday, May 21st, 2016. From Lisbon to Lahore, from Belgrade to B... ]]>
                </description>
                <link>https://www.freecodecamp.org/news/waking-up-a-sleeping-city-with-javascript-3b9740e094bd/</link>
                <guid isPermaLink="false">66c364a5139b845d61e84bab</guid>
                
                    <category>
                        <![CDATA[ events ]]>
                    </category>
                
                    <category>
                        <![CDATA[ india ]]>
                    </category>
                
                    <category>
                        <![CDATA[ Node.js ]]>
                    </category>
                
                    <category>
                        <![CDATA[ General Programming ]]>
                    </category>
                
                    <category>
                        <![CDATA[ tech  ]]>
                    </category>
                
                <dc:creator>
                    <![CDATA[ freeCodeCamp ]]>
                </dc:creator>
                <pubDate>Sat, 28 May 2016 09:11:23 +0000</pubDate>
                <media:content url="https://cdn-media-1.freecodecamp.org/images/1*v4Lqx0NQIeTugNA9w_AlLg.jpeg" medium="image" />
                <content:encoded>
                    <![CDATA[ <p>By Koustuv Sinha</p>
<p>Not once, but twice, our college became a part of an International community of highly productive and engaging people. The most recent installment took place on last Saturday, May 21st, 2016. From Lisbon to Lahore, from Belgrade to Bengaluru, from Berlin to Bainbridge, we all came together on a single day to celebrate a Global event, a fun event of teaching, learning &amp; hacking together the concepts of JavaScript / NodeJS. Divided by borders, united by JavaScript! Yes, I’m talking about <a target="_blank" href="http://nodeschool.io/international-day">NodeSchool International Day</a>!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/6k2Eq4IVWPU4th2C3Yflhot8fq02QIUCtzGa" alt="Image" width="800" height="262" loading="lazy"></p>
<h4 id="heading-a-brief-history-of-nodeschool">A brief history of NodeSchool</h4>
<p>On a fine day, a few people from a little upcoming community of daring open source hackers decided to challenge the world with the powers of a language that others dismissed as “too slow”, “a toy language”, and “web only”. They came together to build what would be a simple “<a target="_blank" href="https://github.com/workshopper/workshopper">workshopper</a>” module, called <a target="_blank" href="https://github.com/substack/stream-adventure">stream-adventure</a>.</p>
<p>What’s a workshopper? It’s a simple framework displaying a set of challenges to be completed right in your terminal, and has a test runner incorporated within it to test your code solutions.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/suW-XpjrCxnhcI8K4o8seqWbUplsRm2mMlBR" alt="Image" width="700" height="529" loading="lazy">
<em>javascripting Workshopper</em></p>
<p>These guys then went on to create the initial workshopper modules, such as <a target="_blank" href="https://github.com/sethvincent/javascripting">javascripting</a> and <a target="_blank" href="https://github.com/workshopper/learnyounode">learnyounode</a>, which consisted of beginner level JS and NodeJS problems. They thought, “Well, this is fun. We should have an event focused on these things!”</p>
<p>Soon, ideas came pouring in, which became modules in the NodeJS ecosystem (npm). Participants created repositories and set up websites. And in late 2013, the first official NodeSchool event was underway in Silicon Valley.</p>
<p>The community started to grow, and local chapters sprang up all over the world. By May 2016, there were more than 165 worldwide city-based chapters, which have hosted more than 500 events so far!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/5dXhvDvhHexwG51SzLwExrUatlxrGTFl05bh" alt="Image" width="577" height="387" loading="lazy">
<em>NodeSchool Upcoming and Past Events</em></p>
<h4 id="heading-node-comes-to-kolkata">Node Comes to Kolkata</h4>
<p>In July of last year, I hit upon the idea of hosting a NodeSchool event in my city. Tech-wise, Kolkata is a laid back city with few meetups or hackathons to speak of. Most of the cool events are either in Bangalore or Hyderabad. We have an IT Park — known here as Sector V — which was a promised utopia of budding startups and big companies alike. But let’s just say that it hasn’t flourished as much as those of other metropolitan areas in India.</p>
<p>There are tech companies here, but most are service based. There isn’t much of a product or startup footprint. Undergraduates and graduates in my city miss out on the most important medium for networking and skill learning just because of the current landscape. And thus, they resort to joining service-based IT behemoths, which just treat them as a disposable resource.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ZqIL9kabTYRnK1TkFC8mPmcDCZ5ikMUrF0RM" alt="Image" width="800" height="235" loading="lazy">
<em>Sector V, Kolkata, India</em></p>
<p>With only a short time to set everything up, I reached out to a NodeSchool core team member, <a target="_blank" href="https://github.com/SomeoneWeird">Adam Brady</a>, and asked him to guide me. I had three priorities for the event:</p>
<ul>
<li>Create awareness in my city and my college</li>
<li>Train college students and help them shape up with new technologies</li>
<li>Put our college to the global map</li>
</ul>
<p>All NodeSchool Chapters are city based. This meant that, technically speaking, I had to host NodeSchool Kolkata. But due to time and space constraints, I had a better idea. Why not setup a smaller college-level chapter instead? After talking it over with Adam, he agreed to my proposal, and hence the <a target="_blank" href="https://github.com/nodeschool/iem-kolkata">NodeSchool IEM Kolkata Chapter</a> was born on August 2015.</p>
<p>We had our inaugural workshop on August 31st, 2015, with 25 participants. Together, we coded together on mainly beginner NodeSchool modules using JavaScript and Git.</p>
<p>As far as new beginnings go, it exceeded my expectations, to say the least! The attendees went home with a little hands-on knowledge, some freebie stickers, and a lot more confidence! <a target="_blank" href="http://iem.edu.in/">IEM Kolkata</a> was added to the world map, and <a target="_blank" href="https://github.com/maxogden">Max Odgen</a> (principle founder of NodeSchool) <a target="_blank" href="https://github.com/nodeschool/iem-kolkata/issues/3">commented on our pics</a>!</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/OygUH0qBwjbUVKZTFMQxRZMjc8kYSC59mIiQ" alt="Image" width="800" height="414" loading="lazy">
<em>NodeSchool Workshop in IEM Kolkata on 31st August, 2015</em></p>
<p>As the Second Law of Thermodynamics predicts, post workshop, the interest disappeared to a minimum. But that didn’t deter me from my goal. I found a few long-term interested people, and started a little newsletter among them. We kept in touch, and shared important links, resources, and tutorials among ourselves.</p>
<p>Fast forward to May 2016. NodeSchool International Day was just right around the corner, and planning started barely one week before it! <a target="_blank" href="https://github.com/hkiem">Himanshu Kashyap</a>, a final-year student, helped me out this time by publicizing the event, handling back-end tasks, and mentoring. We sent out invitations, cached the workshop software so we could use it offline, configured our website, and enrolled in the International Day Chapter. We were get-set-go for the event! We even got the <a target="_blank" href="https://www.isoeh.com/">Indian School of Ethical Hacking</a> — a startup founded by our alumnus <a target="_blank" href="https://www.linkedin.com/in/kiritsankargupta">Kirit Sankar Gupta</a> — to sponsor the event!</p>
<p>Nature worked against us this time. Heavy rains throughout the city prevented half the people who had already registered for the event from showing up. Still we went ahead, with the true spirit of Nodeschool International Day, and started the proceedings with the Bengaluru and Osaka teams.</p>
<p>Last time we had some hiccups setting everything up, but this time since the workshops were already cached in my system (<a target="_blank" href="https://github.com/nolanlawson/local-npm">local-npm</a>), and installations were a breeze.</p>
<p>By lunchtime, everyone had completed the basic <em>javascripting</em> module, and was hungry for more! After lunch, we proceeded with Git, Github, and NodeJS basics with the <em>git-it</em> and <em>learnyounode</em> module. We also had a live <a target="_blank" href="https://appear.in/">Appear.in</a> chat with <a target="_blank" href="https://github.com/iancrowther">Ian Crowther</a>, <a target="_blank" href="http://nodeschool.io/london/">London</a> Chapter host, as well as the <a target="_blank" href="http://nodeschool.io/tokyo/">Tokyo</a> and <a target="_blank" href="http://nodeschool.io/berlin/">Berlin</a> Chapters! At the end of the day, we distributed stickers and coasters, and then popped by Bisk Farm for a round of snacks and drinks.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/ZZtD1LrX8Ub9GvsBZyzdoYUomiDglanaTrCe" alt="Image" width="800" height="600" loading="lazy"></p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/XEI4OeClHil2lsiSRGV1UU4m5vMbotZsbYpO" alt="Image" width="800" height="600" loading="lazy"></p>
<p>I eventually plan to merge our chapter with a bigger NodeSchool Kolkata chapter once we get enough interested people. It takes time to develop interest and awareness in our city, but we should all strive for it nonetheless.</p>
<p>According to The Guardian, India will have <a target="_blank" href="https://www.theguardian.com/books/2016/apr/24/somini-sengupta-the-end-of-karma-interview">over 1 million people turning 18</a> every month for the next two to three years! That is a huge load for our society to bear at once. Also, our country is facing an acute shortage of skilled engineers, and 80% of the current crop of engineers are considered unemployable by some <a target="_blank" href="http://timesofindia.indiatimes.com/tech/tech-news/Over-80-of-engineering-graduates-in-India-unemployable-Study/articleshow/50704157.cms">studies</a>. Why? Causes range from mediocre engineering colleges, low quality classroom education, less opportunity, and most importantly, less networking.</p>
<p>Not all is bad about my city, though. We are experiencing a slow influx of city-based startups, thanks to some cool entrepreneurs, such as <a target="_blank" href="https://www.linkedin.com/in/chawlasumeet">Sumeet Chawla</a>, who founded <a target="_blank" href="http://juststickers.in/">JustStickers.in</a>, where we buy cool stickers and coasters for our events. His love for this city dragged him away from Bangalore, and he brought back his experience and immediately put it to use. We need more entrepreneurs like him to build innovative products and in turn help our city inch toward becoming a more technology-friendly place.</p>
<p><img src="https://cdn-media-1.freecodecamp.org/images/pBOZ-jMxAAeq74XrU2o-SDWvzaLHWB4BRQWd" alt="Image" width="800" height="600" loading="lazy">
<em>Stickers and Coasters from JustStickers at our Nodeschool Event, May 2016</em></p>
<p>Members of NodeSchool and Free Code Camp communities have something much more important than raw expertise. They have heart, a desire to network, and an eagerness to help others. This drives up the competency level of each and every participant.</p>
<p><strong>Collaboration is the key to success.</strong> We hope to build a better tech community in our city by holding regular events like Nodeschool, Free Code Camp, and keep pushing our city toward becoming a more informed, skilled and proactive generation.</p>
<p>Join me in this Quest. <strong>For the <a target="_blank" href="https://www.quora.com/Why-was-Kolkata-given-the-nickname-City-of-Joy">City of Joy</a></strong>.</p>
<p><em>Many thanks to <a target="_blank" href="https://github.com/alayek">Arijit Layek</a> for the awesome edits and constant motivation. If you would like to get in touch, contact me on <a target="_blank" href="https://gitter.im/koustuvsinha">Gitter</a>. <a target="_blank" href="https://gitter.im/nodeschool/kolkata">Help us plan</a> a bigger Nodeschool Kolkata event.</em></p>
 ]]>
                </content:encoded>
            </item>
        
    </channel>
</rss>
