Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.)

like image 223
Stephen Avatar asked Dec 04 '22 08:12

Stephen


2 Answers

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.

like image 185
Pointy Avatar answered Dec 28 '22 07:12

Pointy


You can access event.target, which will be the element that started the event.

$('.myList').click(function(event) {
   var target = $(event.target);
});

jsFiddle.

However, Pointy's answer seems to be easier to use.

like image 42
alex Avatar answered Dec 28 '22 08:12

alex