Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

While bouncing around StackOverflow, I\'ve noticed a number of people attaching

ID: 647017 • Letter: W

Question

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?

Explanation / Answer

There is one advantage: If #myButton isn't always on the page (that is, it's inserted through AJAX or altering innerHTML or the DOM directly), then there's no need to recreate the event listener over and over.

That said, you shouldn't do it due to both performance and obfuscation. If this is happening on your page, at least put the event on a containing element that is always there - #content or #menu or something similar.

And even then, to address the example code in your question, jQuery in particular has syntax to do that without manual checking:

$(document).on('click', '#myButton', function() { ... });
Although, as I said above, it is better to restrict the event to where it can appear:

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