Attaching Events to Document Better Than Attaching Them to Elements?

Posted by Todd on Programmers See other posts from Programmers or by Todd
Published on 2013-10-20T17:16:58Z Indexed on 2013/10/20 22:10 UTC
Read the original article Hit count: 182

While bouncing around StackOverflow, I've noticed a number of people attaching events (notably click events) to the document as opposed to the elements themselves.

Example:

Given this:

<button id="myButton">CLICK ME</button>

Instead of writing this (using jQuery just for brevity):

$('#myButton').on('click', function() { ... });

They do this:

$(document).on('click', function() { ... });

And then presumably use event.target to drill down to the element that was actually clicked.

Are there any gains/advantages in capturing events at the document level instead of at the element level?

© Programmers or respective owner

Related posts about JavaScript

Related posts about event-programming