0

Using CSS, it's very easy to attach a certain style for all elements sharing the same class. I would like to do something similar, but for DOM event handlers rather than styles. E.g. I'd like all elements with class my-class will have the same handler for a click event.

I know this can be done easily using a selector after the page is loaded, e.g. in jQuery:

$('.my-class').click(function() {alert('clicked');})

but I wonder if this can be achieved using DOM event delegation. The canonical answer suggests that delegation can be used to propagate an event from a child node to its parent (or ancestor, in general). Is it possible to define a handler on a single node with my-class, and have all the other elements with my-class delegate to it, even if they aren't descendents?

Community
  • 1
  • 1
dimid
  • 6,179
  • 1
  • 38
  • 70

2 Answers2

1

Although considered bad practice (because you should generally delegate to the nearest static ancestor), you can delegate to the body element as follows:

$('body').on('click', '.my-class', function() {
    alert('clicked');
});

This will of course delegate click events on any elements with a class of my-class that are in the body of your document.

BenM
  • 49,881
  • 23
  • 107
  • 158
0

We can also trigger the event when a different element is clicked:

$( "#other" ).click(function() {
  $( "#target" ).click();
});
Ankur Shah
  • 396
  • 3
  • 14