0
I have a chat that was developed in Bootstrap, PHP, Mysql and Jquery. The structure is like this:
HMTL
<div class="chat-panel panel panel-primary chat-boder chat-panel-head" >
<div class="panel-heading">
<i class="fa fa-comments fa-lg"></i>
Chat
</div>
<div id="mensagens"></div>
<div class="panel-footer">
<form onsubmit="enviar();return false" method="post" action="">
<div class="input-group">
<input id="mensagem" type="text" class="form-control input-sm" placeholder="Coloque sua mensagem..." />
<span class="input-group-btn">
<button type="submit" class="btn btn-primary btn-sm">
Enviar
</button>
</span>
</div>
</form>
</div>
</div>
Jquery
$(document).ready(function() {
var variavel = document.getElementById("mensagens").scrollHeight;
$("#mensagens").animate({scrollTop: variavel},3000);
carregarmensagens();
setInterval(function(){
carregarmensagens();
},1000);
});
function carregarmensagens() {
var url;
url = "chat/ver-mensagens.php";
jQuery.get(url,function(data) {
$("#mensagens").empty().append(data);
});
}
function enviar() {
var url;
var mensagem;
var enviando;
url = "chat/enviar-mensagem.php";
mensagem = $("#mensagem").val();
enviando = $.post(url, {mensagem:mensagem});
enviando.done(function() {
document.getElementById("mensagem").value = "";
carregarmensagens();
});
}
chat/view-messages.php
<div class="panel-body">
<ul class="chat-box">
<?php
while($jm = mysqli_fetch_object($sql)){
....
<li class="<?php echo $class; ?> clearfix" style="background-color: <?php echo $fundo; ?>">
<span class="chat-img <?php echo $pull; ?>">
<img src="<?php echo $img; ?>" alt="Admin" class="img-circle" style="width: 60px" />
</span>
<div class="chat-body clearfix">
<small class=" text-muted">
<i class="fa fa-clock-o fa-fw"></i>?php $jm->Hora; ?></small>
<strong class="<?php echo $pull; ?>"><?php echo $jm->Usuarios; ?></strong>
<p>
<?php echo $jm->Mensagem; ?>
</p>
</div>
</li>
<?php } ?>
The problem is that the scroll gets stuck at the top, I can’t keep up with the chat. How could I fix this?
Hello Matthew... worked in parts, the scroll went down, but now when I type something in the chat, the scroll does not follow the conversation....
– user24136
For it to accompany you need to call the code again
$('#mensagens').animate({ 'scrollTop' : $(document).height() }, 1);
so that the scroll is updated down to every message sent.– Mateus Spadacio
Right... forgive me the ignorance, but I’m a layman in Jquery. How would I call you again?
– user24136
Put him in the method
enviar()
also.– Mateus Spadacio
Thank you Matthew.
– user24136