简体   繁体   中英

Django Chat App - Can't automatically scroll down live chat box when new messages are added

So I'm making a chat app with Django Channels, Javascript, and HTML/CSS. I am really not that familiar at all with front-end but so far everything seems to be working fine with my chat app except for the chat box itself not moving downwards when new messages are added.

I set my CSS .chatbox class to have an overflow: scroll , but adding that won't make the box auto-scroll when new messages are inserted. I assume based on research I need to alter my javascript script but I honestly don't know where to start. Again, please go slow with me lol I'm not really familiar with frontend.

Current Javascript:

  <script>
    const chatLog = document.querySelector('#chat-log');
    const chatSocket = new WebSocket("ws://" + window.location.host + "/");

    if (!chatLog.hasChildNodes()) {
      const emptyText = document.createElement('h3')
      emptyText.id = 'emptyText'
      emptyText.innerText = 'No Messages'
      emptyText.className = 'empty Text'
      chatLog.appendChild(emptyText)
    };

    chatSocket.onopen = function (e) {
      console.log("The connection was setup successfully !");
    };

    chatSocket.onclose = function (e) {
      console.log("Something unexpected happened !");
    };

    document.querySelector("#id_message_send_input").focus();
    document.querySelector("#id_message_send_input").onkeyup = function (e) {
      if (e.keyCode == 13) {
        document.querySelector("#id_message_send_button").click();
      }
    };

    document.querySelector("#id_message_send_button").onclick = function (e) {
      var messageInput = document.querySelector("#id_message_send_input");
      message = messageInput.value;
      chatSocket.send(JSON.stringify({ message: message, username : "{{request.user.username}}"}));
      messageInput.value = "";
    };


    chatSocket.onmessage = function (e) {
      const data = JSON.parse(e.data);
      const messageElement = document.createElement('div');
      const userId = data['user_id']
      const loggedInUserId = JSON.parse(document.getElementById('user_id').textContent)
      messageElement.innerText = data.username + " : " + data.message;
      //messageElement.className = 'message'
      if (userId === loggedInUserId) {
        messageElement.classList.add('message', 'sender')
      } else {
        messageElement.classList.add('message', 'receiver')
      }


      chatLog.appendChild(messageElement)

      if (document.querySelector('#emptyText')) {
        document.querySelector('#emptyText').remove()
      }
    };
  </script>

current chatbox CSS:

.chatbox {
    height: 55vh;
    margin-top: 20px;
    overflow: scroll;
}

I feel you man. It's a pain. It depends what element chatLog is. If it's a list item inside a ul, it wouldn't update it's containers size to auto-scroll down to. So it wouldn't for other HTML Elements.

I had to solve it manually by setting a new size each time a message is added.

Something like:

document.getElementById('chat_content').height = base.offsetHeight-25;

var chat_contents = document.getElementsByClassName('chat_content');
    
for (var i=0; i<chat_contents .length;i++) {
    chat_contents[i].height = document.getElementById('chat_content').height;
}
    
document.getElementById('scrollable_chat_text').height = (base.offsetHeight-76);
    
chat_contents= document.getElementsByClassName('scrollable_chat_text');
for (i=0; i<chat_contents.length;i++) {
    chat_contents[i].height = (base.offsetHeight-76);
}

Don't ask me about "25" or "76" that's probably some pixel shifting "bs" I did back then to adjust for some design reasons.

I also added a dummy line at the end (remove it, add the new chat message, add it back) to get it scroll down properly to the very end

<li><span class="noselect" style="color:#FFFFFF;">ScrollHack</span></li>

Let me know if this is the right direction for you

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM