JavaScript Cross-Browser Event Target: Two Approaches Quiz
Two seeded approaches to read the event target across browsers (event.target plus legacy event.srcElement, and a delegated table cell editor), plus two companions on currentTarget and composedPath.
340 views
7
Implement getEventTarget(e) that returns the originating DOM element across modern browsers AND legacy IE. Use the event.target || event.srcElement fallback, and normalize the window.event global as the very first step.
Examples
Example 1:
Input: a click event in Chrome
Output: the clicked element via event.target
Explanation: Modern browsers expose `target` directly; the `|| srcElement` branch is never taken.Example 2:
Input: a click event in IE 8
Output: the clicked element via event.srcElement
Explanation: Old IE attached the event to `window.event` and exposed `srcElement` instead of `target`.function getEventTarget(e) {
// your solution comes here, supporting modern + IE 8
}Use getEventTarget inside a delegated click handler on a <table>. The handler should only fire when the clicked element is a <td>. Implement the table-level editCell glue.
Examples
Example 1:
Input: user clicks a TD inside the table
Output: editCell receives the TD as the target
Explanation: getEventTarget unwraps the legacy/modern difference, then `tagName.toLowerCase()` gates on the cell tag.function getEventTarget(e) {
e = e || window.event;
return e.target || e.srcElement;
}
function editCell(e) {
// your solution comes here, gating on <td>
}Explain the difference between event.target and event.currentTarget inside a delegated handler. Which one is the right choice for editCell from Q2, and why?
Examples
Example 1:
Input: click on a <span> inside a <td> inside a <table> with a click listener
Output: event.target = <span>, event.currentTarget = <table>
Explanation: target is where the event originated; currentTarget is the element the listener is bound to.// In your answer, walk the target chain for a click on <span> inside <td> inside <table>.
function explain() {
return 'event.target = origin element; event.currentTarget = bound element';
}Shadow DOM gotcha: inside a custom element with mode: 'open', what does event.target return for a click that originated INSIDE the shadow tree? How do you recover the inner element?
Examples
Example 1:
Input: a click inside a shadow root listened to from the light DOM
Output: event.target is the SHADOW HOST, not the inner element
Explanation: Event retargeting masks the shadow DOM internals so the light DOM does not see implementation details.// Sketch only; runs in a browser with custom elements support.
function handleClick(e) {
const inner = e.composedPath()[0];
return inner;
}