jQuery fails to register a click event on a child element

I've designed a div element to serve as a contact list, containing other divs within it. I'm attempting to set up a click handler on each list item (inner div) but the click event is not being 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>

When I assign a click handler to the parent DOM object, it works as expected. Is there something I'm overlooking?

EDIT:

It just occurred to me that I forgot to mention how children are added:

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

Here, the variables "d" and "id" are populated from a successful server call.

Answer №1

you have

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

instead of

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

ensure you include this event trigger within the document load event to make it work correctly:

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

Edit:

It's worth noting that the class name should be without single quotes, as shown below:

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

Edit 2

An alternative approach would be using the children() method:

$(function(){
    $(".contacts").children("div").on("click",function(){
        alert("clicked");
    });
});

Answer №2

An improved method for organizing this event is to place it within a document ready function that loads with the page, while also utilizing the .click jQuery function. This shorthand version stands in for .on("click", FUNCTION).

For instance:

$(document).ready(function(){
    $(".contact").click(function(){
        alert("clicked");
    });
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble handling Ajax response

I have two JSP files described below. The parent JSP page contains a Select dropdown box with two options. Another JSP file, dispTable.jsp, displays select boxes inside a table. If the user selects "one" from the dropdown in the parent.jsp page, I want ...

React Native App experiences immediate crashes when launched on TestFlight

I've encountered a frustrating issue with my application that keeps crashing when loaded into Testflight. To troubleshoot, I decided to start from scratch and created a basic expo react native application to pinpoint the source of the problem. After ...

When I change the camera, the camera control becomes active

I needed to switch the camera type in my three.js Demo, so I referred to an official demo at: However, I encountered some errors when testing my demo. Pressing 'P' to use the cameraPerspective worked fine, but when I tried to switch to cameraOrt ...

Reviewing and Implementing React and Material-UI Autocomplete for Selecting Multiple

Having trouble using Formik and MUI Autocomplete with multiple items. Specifically, when searching for "Pencil", it doesn't highlight the item. Also, you can select it twice by clicking on it. Desired outcome: Being able to select one or more items. ...

Switch the modal trigger from clicking to loading with a delay in time

I have been experimenting with a simple modal plugin that I downloaded and modified to better understand its functionality. One thing I am curious about is how to change the trigger from an 'on click' event to an 'on load' event with a ...

Another Option Besides HTTP Client Hints

I am interested in finding a solution where a server app can return an image that perfectly fits the entire device screen regardless of its orientation. Recently, I discovered the HTTP Client Hints method which allows browsers to send information like scr ...

Add the directive prior to rendering the HTML

I attempted to comprehend the problem below: My html string is rendered using ng-bind-html I successfully replaced a specific placeholder in the html string with a directive (or multiple). For example, I changed [placeholder]test[/placeholder] to <my- ...

Are the CSS flow arrows suffering from poor formatting?

https://i.sstatic.net/ni3vf.pngAfter tinkering with code from three different individuals to create CSS arrows, I fear I may have overcomplicated things. Is there any CSS expert out there who can help me streamline this? I'm struggling to adjust the p ...

ERROR: The data has reached its end prematurely (data length = 0, requested index = 4). Could this be a corrupted zip file?

Currently, I am developing a WhatsApp bot and storing the chat data in an Excel file using exceljs for further processing. In order to handle responses efficiently, I am utilizing promises to resolve them. Below is the function I have created to read the c ...

Having difficulty including the Column Name in the Jqgrid footer for sum calculation

I was working on the Jqgrid code and found a way to display the sum correctly in the footer of the grid. var colSum = $("#dataGrid").jqGrid('getCol', 'Amount', false, 'sum'); $("#dataGrid").jqGrid('footerData', &a ...

Ways to trigger the onclick event from different controls

I have a videojs player and a button on my html page. The videojs player supports the functionality to pause/play the video when clicked. I want to trigger this event by clicking on my button. How can I achieve this? Here is the code that I tried, but it ...

Bootstrap v5 does not automatically close the navbar

Currently utilizing Bootstrap v5 and encountering an issue with the navbar. I directly copied the code snippet from this site, but unfortunately, the navbar is not functioning as expected. The navbar opens, but upon clicking again on the button, it fails t ...

The POST Request will exclusively provide the ID in JSON format without including any other data

Trying to make a POST request from Postman to Mongo Database. Currently, only the ID of the object is being returned and the data is not displaying. Data Model: const mongoose = require("mongoose"); const categorySchema = mongoose.Schema({ name: String, ...

Ensure that the table tag in testWeb(jspackage.JSAssignmentDiscount) contains exactly 3 rows and assess whether it complies with the CSS criteria for tables and table rows

Criteria: The table must include the product name, product price, and season information. The product name and product price should be input text boxes labeled with name and price respectively. The season selection should be a dropdown menu labeled with s ...

What is the best way to center content without aligning text in the center using Bootstrap?

When using Bootstrap, I have divided my main page into two grids to enable content to stack vertically in mobile view. However, I am struggling to center the text horizontally and vertically within the grid without aligning the text to the center using the ...

Ways to center text vertically alongside an image

<ion-view view-title="个人信息"> <ion-content> <style> .user-details { display: flex; align-items: center; justify-content: space-between; height: 80px; } .us ...

Angular: Trigger service worker to handle push notification event from service

Is it possible to call the service worker push event from a custom service in Angular? I implemented this code in my service, and it works on desktop and android, but not on iPhone. navigator.serviceWorker.register('sw.js'); Notification.request ...

Struggling to make an AJAX form function properly

I'm running into an issue while setting up a basic AJAX form. My goal is to have a message display on the same page upon successful login using a PHP form through AJAX, but currently, I get redirected to the PHP file after form submission. Can anyone ...

The React/Redux application is experiencing difficulties with API calls, as they are returning empty responses and the actions are not being triggered

Hey there, I'm currently working on a React Native app and running into some issues with making API get requests. It seems like the response is throwing an error and the action isn't executing properly. I'll share my code below, so if anyone ...

Issue with Vuetifyjs theme variable failing to function properly in version 1.0.0

Check out the step-by-step instructions provided in https://vuetifyjs.com/en/style/theme. I successfully changed the theme using the code below with vuetifyjs version 0.13.0. However, after updating to vuetifyjs 1.0.5, the font still displays correctly bu ...