Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

106
Views
Global onclick handler vs. per-element event handlers

Consider this example:
You're creating a website that uses client-side rendering. When the user clicks a link, you want to disable the browser's navigation and render the new page yourself.

Perhaps you also have some html like this, and you want to call upvote_post(id) every time the button is clicked:

<post-element data-id=12345> 
   ... 
   <upvote-button></upvote-button>
</post-element>

The common way to handle both of these cases would be to add a click event handler on every <a>, <upvote-button>, etc. element that you generate.

But wouldn't it be better to just add an event handler on the document itself?

document.addEventListener('click', function(e) {
    for (let elem of e.path) {
        if (elem instanceof HTMLAnchorElement && elem.origin==window.location.origin) {
            e.preventDefault()
            render_page(elem.href)
            break
        } else if (elem.tagName=='UPVOTE-BUTTON') {
            let post = elem.closest('post-element')
            upvote_post(post.dataset.id)
            break
        }
    }
})

Of course, it feels wrong to bypass the builtin event handler system, but I can't think of any disadvantages here.
You can still add event handlers to specific elements if you need to, but for common actions, this seems like a better solution.

about 4 years ago · Juan Pablo Isaza
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!