Search code examples
javascriptjqueryeventsevent-handlingevent-bubbling

jQuery: binding a single event listener that can handle events of its children


I encountered a question to which I didn't know the solution for.

Suppose I have this HTML markup (dynamically generated by the server or simply a static file):

<ul class="myList">
<li><a href="page1.html">Page 1</a></li>
<li><a href="page2.html">Page 2</a></li>
<li><a href="page3.html">Page 3</a></li>
<li><a href="page4.html">Page 4</a></li>
<li><a href="page5.html">Page 5</a></li>
<li><a href="page6.html">Page 6</a></li>
<!-- ... -->
<li><a href="page1000.html">Page 1000</a></li>
</ul>

I want to bind a click event handler to the <a> tag. Normally, I would write out

$('.myList').find('a').click(function() {});  /* Or something similar */

which would perform implicit iteration on all the anchor tags to bind a click event to each of them. However, I was told that this is an expensive operation.

I was asked if there was some way to attach only one event listener (on the ul tag) and use event bubbling to figure out which anchor tag was clicked. I have never encountered something like this, so I didn't know the answer. Apparently, there is an answer. Does anybody know how to place a single event listener on an element and have it figure out which child element was clicked? (I still need to use event.preventDefault() to prevent the default click event.)


Solution

  • Check out delegate() — it's exactly what you're asking for.

    $('ul.mylist').delegate('a', 'click', function() {
      // ... your code ...
    });
    

    You get all the benefits of a jQuery handler, without having to do the binding to all those elements.