Unable to reference a css class in jQuery for elements generated using jQuery

I am encountering an issue with my jQuery code related to designing a chat application. The problem arises when trying to display the users list received from the backend through ajax in the frontend. Although I can successfully obtain and display the data, I face a challenge when creating elements with CSS classes using jQuery and then referencing those classes within the same jQuery file. Below is the code snippet that illustrates my concern:

function display_users_list(html) {
    var users_list = JSON.parse(html);
    var display_users = '';
    for (var key in users_list) {
        display_users += '<div class="user user-list" data-user-id='+users_list[key].userid+'>';
        display_users += users_list[key].username;
        display_users += '</div>';
    }
    $(".chat-body").html(display_users);
}

Specifically, the problem occurs when attempting to call a CSS class named "user-list" on elements created using jQuery. Here is the relevant portion of code demonstrating this issue:

$(".chat-body > .user-list").each(function() {
    $(this).on("click", function() {
        var uId = $(this).data('user-id');
        var innerTxt = $(this).text();
        console.log("uid:"+uId+"innerTxt:"+innerTxt);
        //$(".chat-box").after(generate_msg_box(uId, innerTxt))
    });
});

The entire set of code consists of HTML markup as shown below:

<div class="chat-box">
    <div class="chat-head">Users List</div>
    <div class="chat-body">
        No User Found
    </div>
</div>

<div class="msg-box">
    <div class="msg-head">
        User 1
        <div class="close-msg">x</div>
    </div>
    <div class="msg-wrap">
        <div class="msg-body">
            <div class="sender-msg">This is sender message</div>
            <div class="recevier-msg">This is recevier message</div>
            <div class="sender-msg">This is sender message</div>
            <div class="recevier-msg">This is recevier message</div>
            <div class="sender-msg">This is sender message</div>
            <div class="recevier-msg">This is recevier message</div>
            <div class="recevier-msg">This is recevier message</div>
        </div>
        <div class="msg-footer">
            <textarea class="msg-input">Sample</textarea>
        </div>
    </div>
</div>

And the respective jQuery code segment:

$(document).ready(function() {
$(".msg-box").hide();
get_users_list();
$(".chat-head").click(function() {
    $(".chat-body").slideToggle("slow");
});

function get_users_list() {
    $.ajax({
        url: "phpActions/actions.php",
        method: "post",
        data: "actions=getData",
        success:function(html) {
            display_users_list(html);
        }
    });
}

function display_users_list(html) {
    var users_list = JSON.parse(html);
    var display_users = '';
    for (var key in users_list) {
        display_users += '<div class="user user-list" data-user-id='+users_list[key].userid+'>';
        display_users += users_list[key].username;
        display_users += '</div>';
    }
    $(".chat-body").html(display_users);
}

$(".chat-body > .user-list").each(function() {
    $(this).on("click", function() {
        var uId = $(this).data('user-id');
        var innerTxt = $(this).text();
        console.log("uid:"+uId+"innerTxt:"+innerTxt);
        //$(".chat-box").after(generate_msg_box(uId, innerTxt))
    });
});

});

Answer №1

By utilizing jQuery.on() as you currently are, you have the opportunity to optimize your event handling process by implementing delegated events and eliminating the need for an event binding loop. Delegated events ensure that your events will still be triggered even on elements added to the page at a later time, which aligns perfectly with your situation.

According to the documentation:

Delegated events offer the benefit of being able to handle events from descendant elements that may be inserted into the document after the event handler is set up. By selecting an element that is guaranteed to exist when the delegated event handler is attached, you can leverage delegated events to avoid constantly attaching and removing event handlers.

$(".chat-body").on("click", ".user-list", function(event) {
  var $listElement = $(event.target);
  var uId = $listElement.data('user-id');
  var innerTxt = $listElement.text();
  console.log("uid:" + uId + "innerTxt:" + innerTxt);
});

Answer №2

It seems like you may be binding the click function too early, before the element is actually loaded onto the DOM. Double check to ensure that your event binding code comes after the line $(".chat-body").html(display_users);

Based on your current code, it appears that the event binding call is happening before the ajax calls return the necessary data. To fix this issue, try creating a new function specifically for event binding.

function bindClick() {
    $(".chat-body > .user-list").each(function() {
        $(this).on("click", function() {
            var uId = $(this).data('user-id');
            var innerTxt = $(this).text();
            console.log("uid:" + uId + "innerTxt:" + innerTxt);
            //$(".chat-box").after(generate_msg_box(uId, innerTxt))
        });
    });
}

After updating your code to include the above function, make sure to call it after the line:

$(".chat-body").html(display_users);
bindClick();

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

Ways to add AJAX information to select2

I am currently utilizing a select2 dropdown feature and I am attempting to configure it in such a way that it dynamically displays the leads based on the JSON response. As you can observe in the image provided below, the text correctly yields a JSON array ...

Hovering over a link within a paragraph will not trigger the :hover effect

I attempted to apply the :hover effect specifically to a link inside a paragraph. The paragraph with the class .hop is initially hidden, but when I hover over the link, nothing happens. .hop { display: none; } a.hop2:hover + .hop { display: block; } ...

Error: Property cannot be read after page refresh or modification

Upon refreshing or running the project for the first time, I encounter the error: TypeError: Cannot read property 'statements' of undefined This issue is perplexing as the data renders correctly but it appears that the connection is failing. ...

Exploring how to retrieve the input value from an element with ReactJs

Is there a way to determine if an input field contains a value by referencing another element? Here is my approach: <div className='input-item'> <input ref="accessKey" name="username" className="lci-text" type="text"/> & ...

Using the ternary operator in a Python HTML template

Exploring various python ternary operators, I came across this one: a if b else 0 However, it didn't function as expected when I attempted to integrate it into a Django HTML template. {% a if b else 0 %} Here is the specific code snippet that I pl ...

Caution: Attempting to access a non-existent 'sequelize' property within a circular dependency in the module exports

Issue Nodemon server.js [nodemon] 2.0.15 [nodemon] to restart at any time, enter `rs` [nodemon] watching path(s): *.* [nodemon] watching extensions: js,mjs,json [nodemon] starting `node server.js` Warning: connect.session() MemoryStore is not designe ...

Customizing tooltips in SharePoint 2013 for enhanced user experience

I am working with a list that consists of various fields. When hovering over a field, the label name and validated field name are currently displayed. I would like to show a new message explaining what should be filled in that particular field. Additiona ...

Exploring relationships in models: the ultimate guide to querying with @Ngrx/store

In my Angular 2 app utilizing Redux (with @ngrx/store), I have structured the store in the following way: { modelA: { ids: [1, 2], entities: { 1: { name: "name modelA 1" }, 2: { name: "name modelA 2" } } }, mo ...

How can we use AJAX to incorporate a "like" feature?

I have nearly completed my website, but there is one final obstacle. I would like to add an ajax liking feature. The idea is that when a user clicks on the button, an ajax call should be triggered to increase the value in the database and update it on the ...

Unable to place a div below another div

I am in the process of creating a website for my mother, using my limited knowledge. Despite numerous attempts, I have not been able to achieve the desired outcome. Currently, the website looks like this: https://i.stack.imgur.com/ItOcp.jpg However, I e ...

What is the best way to create a shell script using Node.js?

Currently, I am looking to utilize a shell script with NodeJs on my Windows platform to read a CSV file, perform processing via REST API call, and save the output in another CSV file. ...

Adding a new script child to a specific Angular component

Currently, I am including an external JavaScript source in my component using the following method: The Component TypeScript file this.script = this._renderer2.createElement('script'); this.script.type = 'text/javascript'; this.script. ...

What is the best way to set up unique body backgrounds for each page in WordPress?

My website consists of various pages named as : page-X.php page-Y.php page-Z.php These three pages mentioned above require unique background colors. However, the remaining pages/posts on my site inherit their background-color from the style.css file. ...

Turn off the standard sign in prompt when utilizing the NTLM pass-through method in express-ntlm

In my node.js app, I am utilizing the following code with express-ntlm to obtain workstation details: var express = require('express'), ntlm = require('express-ntlm'); var app = express(); app.use(ntlm()); app.all('*', func ...

In search of jQuery AJAX event triggered upon completion of a form file transfer

During a file upload process using the "PECL uploadprogress" status, I have implemented a "beforeunload" warning that pops up when the user tries to close the window while the upload is in progress. $('#form').click(function() { $('#upl ...

Using JavaScript to Redirect to Homepage upon successful Ajax response on local server

I need assistance with redirecting to the Homepage from the SignIn Page once the user credentials have been validated. The response is working correctly, and upon receiving a successful response, I want to navigate to the Homepage. My setup involves Javasc ...

Guide on Triggering a Custom Popup Message upon a Server Action in Next.js

Hey there, I'm currently facing some difficulties in finding the proper way to trigger a toast notification after successfully mutating data using server actions in Nextjs 13. The toast component I'm working with is specifically designed for clie ...

Update the JSON object with new data using JavaScript

After not receiving a proper response on my previous JSON replacement question, I am posting this follow-up query with a more detailed example. var beforeReplacement=[ { "Name": "app1", "id": "1", "groups": [ { ...

Using jQuery, remove any white spaces in a textbox that are copied and pasted

There is a textbox for entering order IDs, consisting of 7 digits. Often, when copying and pasting from an email, extra white spaces are unintentionally included leading to validation errors. I am looking for a jQuery script to be implemented in my Layout ...

Create a customizable JavaScript clock that synchronizes with an image to display the current hour, minute

I am having trouble with my clock not working I have created images for the hour, minute, second, and AM/PM https://i.sstatic.net/4zg00.png I attempted to use this code: <script language="JavaScript1.1"> <!-- /* Live image clock III Written b ...