0

So i came across a code like below:

  var bindEvents = function () {

    $("body").on('click', "a.class1, input.class2, button.class3", function () {
      sendEvents($(this));
    });

  }

And i was wondering why would someone bind the event on body here.

Can't we just do it by directly adding events on a, input and button elements like this:

  var bindEvents = function () {

    $("a.class1, input.class2, button.class3").on('click', function () {
      sendEvents($(this));
    });

  }

Is there any reason why one would use the 1st approach?

D_S_X
  • 848
  • 2
  • 8
  • 27
  • 1
    What's done here is called [event delegation](https://learn.jquery.com/events/event-delegation/) and used to bind event on element which do not exist on the initial page load – empiric May 13 '20 at 11:08
  • Why don't u give one more same class to each of them and using one class name ? – pc_coder May 13 '20 at 11:09
  • 1
    Not exact duplicate but the relevant answer should cover and explain the subject of event delegation – Alon Eitan May 13 '20 at 11:12
  • To complement @AlonEitan 's link, this answer provides some more info on why you need event delegation: https://stackoverflow.com/questions/203198/event-binding-on-dynamically-created-elements – freedomn-m May 13 '20 at 11:46
  • @pc_coder looks like it's a contrived example for demonstration purposes. It's unlikely (I hope...) that OP has `class1` etc – freedomn-m May 13 '20 at 11:46
  • @pc_coder yeah the actual code is somewhat different so ... – D_S_X May 13 '20 at 12:50
  • @AlonEitan To some extent yes. I am looking at the points mentioned under "Here are times when event delegation is required or advantageous:" part in the accepted answer. 1)The elements are not being generated dynamically so that is probably not the reason. 2)However there are a lot of elements to bind this event to, so 2nd reason might be it. But it doesn't completely explain why this approach is good in this case. – D_S_X May 13 '20 at 12:52

0 Answers0