Attaching Events to Document Better Than Attaching Them to Elements?
- by Todd
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?