Course contentsShow
← Web Development
Lesson 768 of 2,98213. DOM EventsFree lesson

Building a Delegated Router Pattern

Creating a reusable delegation pattern for handling navigation links and preventing default browser behavior.

Building a Delegated Router Pattern

You'll learn: How to create a reusable event delegation pattern that handles navigation links throughout your application while preventing default page reloads.

What Is a Delegated Router Pattern?

A delegated router is a centralized event handler that intercepts clicks on navigation links across your entire page. Instead of attaching individual listeners to each link, you use event delegation to catch all link clicks in one place, check where they're going, and prevent the browser's default navigation behavior. This lets you build single-page applications (SPAs) where "navigating" just updates content without reloading the page.

Think of it like a traffic controller at an intersection: rather than placing a separate controller at every single crosswalk, one controller watches the whole intersection and directs traffic based on where each car wants to go.

The Basic Pattern

Here's how you build it:

// Attach ONE listener to the document or container
document.addEventListener('click', function(event) {
  // Use closest() to check if click was on or inside a link
  const link = event.target.closest('a[href^="/"]');
  
  if (link) {
    // Prevent browser from navigating
    event.preventDefault();
    
    // Extract the path
    const path = link.getAttribute('href');
    
    // Handle navigation (update content, change URL, etc.)
    navigateToRoute(path);
  }
});

function navigateToRoute(path) {
  // Your routing logic here
  console.log('Navigating to:', path);
}

This pattern combines delegation, closest() for nested elements, and preventDefault() to stop default behavior—all working together to create a flexible, maintainable routing system.

Key Takeaway: A delegated router pattern uses event delegation to handle all navigation clicks with one listener, preventing default browser behavior and enabling custom routing logic for single-page applications.