global click listener - dormouseroared/dom-inspector-plus GitHub Wiki
That’s a great line to understand — it’s central to how your DOM Inspector works. Let’s break it down step by step:
document.addEventListener('click', function (e) {
if (overlay.contains(e.target)) return
e.preventDefault()
e.stopPropagation()
lastEl = e.target
inspect(lastEl)
}, true)
This code sets up a global click listener so that any time you click anywhere on the page, the inspector will activate — but only if you didn’t click on the inspector itself.
- Adds an event listener for all
click
events on the page. - The third argument
true
makes it run in the capture phase, which means it executes before most other click handlers (like links, buttons, etc).
- Prevents the inspector from re-triggering itself when you click inside the overlay panel.
- If the clicked element (
e.target
) is part of the inspector UI (overlay
), it exits early.
-
Cancels the default action of the clicked element.
- For example: prevents a link from navigating, or a button from submitting a form.
-
Stops the click from bubbling up to other event handlers.
- Ensures that the page’s own JavaScript doesn't react to this click.
- Important for staying out of the way of the page’s normal behavior.
- Stores the clicked element so that the inspector can remember it.
- Useful for restoring state, resetting filters, etc.
- Calls your inspector’s main logic to gather info about the clicked element.
- Displays that info in the inspector UI.
Imagine clicking on this:
<button id="my-button">Click Me</button>
If that button isn’t part of the inspector overlay:
- The page won’t do its default button action
- The inspector opens and shows you the properties of that
<button>
If you’re using Shadow DOM:
- You’ll need to update this line:
if (overlay.contains(e.target)) return
to check both the shadow root and its host:
if (host.contains(e.target)) return
so it excludes the entire inspector UI (inside the shadow) from triggering inspection.
Let me know if you'd like to see a rewritten version that works inside your new Shadow DOM!