Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery alert onclick on element's child?

Tags:

jquery

I'm using this code to display an alert on a certain element:

$("#resultsBox").click(function (event) {
    console.log('a');
    });

I want to display an alert only when you click on 'li' elements inside '#resultsBox'.

I'm trying to do it like this:

$("#resultsBox li").click(function (event) {
    console.log('a');
    });

This is the element's #resultsBox structure:

<div id="resultsBox">
  <ul>
    <li></li>
    <li></li>
  </ul>
</div>

How can this be done?

like image 481
lisovaccaro Avatar asked Aug 08 '12 05:08

lisovaccaro


2 Answers

When you bind an event handler with .click() it applies to any elements that matched your selector at that moment, not to elements later added dynamically.

Given your div is called "resultsBox", it seems reasonable to assume you are actually adding things to it dynamically to display the results of some other operation, in which case you need to use a delegated event handler:

$("#resultsBox").on("click", "li", function (event) {
    console.log('a');
});

This syntax of the .on() method binds a handler to "#resultsBox", but then when the click occurs jQuery checks whether it was on a child element that matches the "li" selector in the second parameter - if so it calls your function, otherwise not.

like image 60
nnnnnn Avatar answered Oct 19 '22 20:10

nnnnnn


Something like this should work

$("#resultsBox").find("li").click(function(){
  alert("You clicked on li " + $(this).text());
});

This should work now: http://jsbin.com/ocejar/2/edit

But anyway, also your example above using $("#resultsBox li") should work just fine. See here. However, using $("#resultsBox").find("li") should be a little faster in terms of performances.

like image 5
Juri Avatar answered Oct 19 '22 19:10

Juri