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