1

I have created a div element which is supposed to be a contact list. It should contain other divs in it. What I'm trying to do, is attach a click handler on each list item (on each inner div). But the click handler is never triggered.

$(".contact").on("click", function() {
  alert("clicked");
});
.contacts {
  position: absolute;
  top: 10px;
  left: 300px;
  width: 100px;
  height: 250px;
  border-color: black;
  border-style: solid;
  z-index: 1;
  overflow: scroll;
}
.contact {
  position: relative;
  width: 80%;
  height: 20%;
  border-style: solid;
  border-color: red;
  z-index: 100;
}
<div id="contactList" class="contacts">
  <div id="1" class="contact">one</div>
  <div id="2" class="contact">two</div>
  <div id="3" class="contact">three</div>
</div>

If I attach a click handler for the parent DOM object, it gets triggered. Am I missing something here?

EDIT:

silly of me, i forgot to mention that children are added this way:

$(".contacts").append($("<div id='"+id+"' class=contact >"+d[contact].name+"</div>"));

where "d" and "id" variables come from a successful server call.

2 Answers2

2

you have

$(".contact").on("click",function(){

instead of

$(".contacts").on("click",function(){

do you have this on trigger in the document is loaded event? it won't work otherwise

$(function(){
    $(".contact").on("click",function(){
        alert("clicked");
    });
});

Edit:

Since the OP forgot to mention something critical, here is my answer to that.

There are no ' around the classname. This should work:

$(".contacts").append($("<div id='"+id+"' class='contact' >"+d[contact].name+"</div>"));

Edit 2

You could also use the children() method:

$(function(){
    $(".contacts").children("div").on("click",function(){
        alert("clicked");
    });
});
Daniël Tulp
  • 1,745
  • 2
  • 22
  • 51
0

A slightly better way of putting this event on is in a document ready function that gets loaded with the page combined with using the .click jquery function. This is short hand for .on("click", FUNCTION).

Example:

$(document).ready(function(){
    $(".contact").click(function(){
        alert("clicked");
    });
});
Keith Enlow
  • 914
  • 6
  • 17
  • how is this better? http://stackoverflow.com/questions/9122078/difference-between-onclick-vs-click – Daniël Tulp Nov 01 '14 at 19:33
  • So that your event handler is not in global space. And since .click most likely calls .on in the jQuery code, I would rather type the short hand version that is more readable for others. The link talks memory, but if you are worried about the couple extra bytes of memory to use .click, then you're application might have other problems on its hands. – Keith Enlow Nov 03 '14 at 16:03
  • without repeating arguments in the linked discussion, the biggest advantage in my eyes is: 'with the [.on()] above, a single handler for all elements that match your selector, including the ones created dynamically' – Daniël Tulp Nov 04 '14 at 14:23