Paris Mavromoustakos
Paris Mavromoustakos

Reputation: 21

jquery does not detect click on child element

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.

Upvotes: 1

Views: 1596

Answers (2)

Dani&#235;l Tulp
Dani&#235;l Tulp

Reputation: 1835

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");
    });
});

Upvotes: 2

Keith Enlow
Keith Enlow

Reputation: 914

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");
    });
});

Upvotes: 0

Related Questions