2

Are there any issues with using Jquery's .on() function as such:

$(document).on("click", "#myDynamicallyLoadedElement", function() {});

vs. something like:

$(".parentElement").on("click", "#myDynamicallyLoadedElement", function() {});

I feel like the $(document) usage would be much more inefficient and could cause performance or other issues with the browser.

Does anyone know if there are any issues with using $(document).on() this way?

kasdega
  • 18,396
  • 12
  • 45
  • 89

2 Answers2

0

You want to narrow it down as much as possible, but avoid repeating yourself, when adding event listeners. Now, there's nothing wrong with $(document) when you actually want to target the whole document, but if not, then you're getting hit by possibly hundreds of events that jQuery must filter — this is a bit inefficient. Rather, it's best to target only the element(s) you want to listen to. For best performance in that example, do this:

$("#myDynamicallyLoadedElement").click(function () {});

Since you used an ID, I assumed there'd be only one of myDynamicallyLoadedElement in the document.

click() is shorthand for on("click", )

rvighne
  • 20,755
  • 11
  • 51
  • 73
0

The two primary reasons to use $(document).on are if you have no idea where you're content is going to be, or if you're defining the event handler prior to the other html being loaded. For most cases neither of these two statements are true, so you should try and be as specific as possible while adhering to the D.R.Y principle.

Nimnam1
  • 515
  • 4
  • 12