Rules Hub
Coding Rules Library
Target document for DOM events and window for viewport events
Attach listeners to `document` for content interactions (clicks, key presses) and reserve `window` for viewport events (resize, scroll) to maintain semantic clarity.
Bad example
| 1 | useEffect(() => { |
| 2 | const handleClickOutside = (e: MouseEvent) => { |
| 3 | // ...logic |
| 4 | }; |
| 5 |
|
| 6 | // Bad: 'window' represents the browser frame, not the content |
| 7 | window.addEventListener('mousedown', handleClickOutside); |
| 8 |
|
| 9 | return () => { |
| 10 | window.removeEventListener('mousedown', handleClickOutside); |
| 11 | }; |
| 12 | }, []); |
Explanation (EN)
Attaching DOM interaction events (like clicks or key presses) to `window` is semantically incorrect because `window` represents the global browser frame. It works due to bubbling but muddies the distinction between viewport state and document content.
Objašnjenje (HR)
Vezivanje događaja interakcije s DOM-om (poput klikova ili pritisaka tipki) na `window` semantički je netočno jer `window` predstavlja globalni okvir preglednika. Iako funkcionira zbog bubblinga, briše granicu između stanja viewporta i sadržaja dokumenta.
Good example
| 1 | useEffect(() => { |
| 2 | const handleClickOutside = (e: MouseEvent) => { |
| 3 | // ...logic |
| 4 | }; |
| 5 |
|
| 6 | // Good: 'document' is the correct root for DOM content interactions |
| 7 | document.addEventListener('mousedown', handleClickOutside); |
| 8 |
|
| 9 | return () => { |
| 10 | document.removeEventListener('mousedown', handleClickOutside); |
| 11 | }; |
| 12 | }, []); |
Explanation (EN)
Using `document` correctly scopes the event listener to the DOM content. Use `window` only for events that actually affect the window frame, such as `resize`, `scroll`, or `hashchange`.
Objašnjenje (HR)
Korištenje `document` objekta ispravno ograničava event listener na sadržaj DOM-a. Koristi `window` samo za događaje koji stvarno utječu na okvir prozora, poput `resize`, `scroll` ili `hashchange`.