Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

403
Visualizações
JQuery - Scroll and anchor to bottom of ajax-driven div unless user scrolls up

I am trying to scroll to the bottom of a div #chat-feed with overflow set to auto and stay there unless a user scrolls that div's content up. If they scroll back down, the div should lock to the bottom and new content will be displayed at the bottom.

Known issues: I have tried implementing this answer with my code but I do not know Javascript well enough yet to get it working. If content from chat-feed.php is taller than the container then the scroll stays at the top. It also seems like the answer given does not respect content loaded from an external file.

Key things: new content should show at the bottom and the div should scroll to the bottom when new content loads UNLESS the users has already scrolled up a bit. If the user scrolls back down, then it should lock to the bottom and new content be displayed at the bottom and be visible.

<div id="chat-feed" style="height: 200px; width: 300px; overflow: auto;"></div>


<script>
$(document).ready(function(){
    setInterval(function(){
        $('#chat-feed').load("chat-feed.php").fadeIn("slow");
    }, 1000);
});
</script>

Demo link

about 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

On question you linked to, there is a better implementation https://stackoverflow.com/a/21067431/1544886.

I've reworked that author's code below:

$(document).ready(function() {

  var out = document.getElementById("chat-feed"); // outer container of messages
  var c = 0; // used only to make the fake messages different

  // generate some chatter every second
  setInterval(function() {

    //check current scroll position BEFORE message is appended to the container
    var isScrolledToBottom = checkIfScrolledBottom();

    // append new mesage here
    $('#chat-feed').append("<div>Some new chat..." + c++ + "</div>").fadeIn("slow");

    // scroll to bottom if scroll position had been at bottom prior
    scrollToBottom(isScrolledToBottom);

  }, 1000);

  function checkIfScrolledBottom() {
    // allow for 1px inaccuracy by adding 1
    return out.scrollHeight - out.clientHeight <= out.scrollTop + 1;
  }

  function scrollToBottom(scrollDown) {
    if (scrollDown)
      out.scrollTop = out.scrollHeight - out.clientHeight;
  }
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<div id="chat-feed" style="height: 150px; width: 300px; overflow: auto;"></div>

UPDATE

JQuery's .load() function deletes the associated element (chat-feed) and re-adds. This means that the out variable points to the old deleted element, not the new. The solution is update the out variable after executing a .load():

$('#chat-feed').load("chat-feed.php").fadeIn("slow");
out = document.getElementById("chat-feed"); // outer container of messages
about 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda