'How to limit jquery output?
Im making a chat and i want to limit for example 5 messages to be displayed. This is what i done so far but its not working.
Edited with important stuff.
function print_msg(msg) {
var output = "";
const exists = document.querySelectorAll("#chat-ul .id_" + msg['id']).length !==0;
if (exists) return;
if(msg["text"].length === 0) return;
output = "<div class='chat'><span class=id_" + msg['id'] +"><img src='../images/avatars/" + msg['avatar'] + "' width='36' height='36' class='border border-2 rounded-circle'> <div class='chat-text text-muted'>" + msg["username"] + "<br><div class='text-dark'>" + msg["text"] + "</div></div></span><br></div>";
$("#chat-ul").append(output);
var length = document.querySelectorAll("#chat-ul>span").length;
while (length >5) {
$('#chat-ul>span:last').hide();
length--;
}
$("#chat-ul").scrollTop($("#chat-ul")[0].scrollHeight);
}
This is the code where message will be displayed:
<div class="col-9 p-0">
<div class="card rounded-0">
<div class="card-header">Chat</div>
<div class="chatbox card-body p-0 d-flex flex-column-reverse">
<div id="chat-loader"></div>
<ul id="chat-ul" style="color:black;"></ul>
</div>
<div class="card-footer text-muted">
<div class="row">
<div class="col">
<input type="text" id="chat-input" class="form-control rounded-pill" placeholder="Type something...">
</div>
<div class="col-auto d-flex justify-content-end">
<button type="submit" id="chat-button" class="btn btn-primary rounded-circle"><i class="fas fa-paper-plane"></i></button>
</div>
</div>
</div>
</div>
</div>
This is where chat is getting messages (from database) as you can see it is limited to 5 there, but it must be limited on function print_msg :
if($q == "load") {
$load = DB::getInstance()->query("SELECT * FROM (SELECT * FROM chat WHERE id > $data ORDER BY id DESC LIMIT 5) AS chat ORDER BY id ASC LIMIT 5");
if($load->count()){
$temparray = array();
foreach($load->results() as $result){
array_push($temparray, $result); //$row je sve iz baze
$data = $result->id;
}
$retr["data"] = $temparray; // Sve iz baze
$retr["id"] = $data; // ID text-a
}else{
$retr["data"] = array();
$retr["id"] = $data;
}
} elseif ($q == "send") {
$insert = DB::getInstance()->insert('chat', array(
'text' => trim($data),
'username' => escape($user->data()->username),
'avatar' => escape($user->getAvatar())
));
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
