Continue the conversation as you scroll down in the chatbox

Struggling to implement an automatic scroll to the bottom of a chat window when a new message appears.

HTML:

<div class="content chat-body" id="messages">
    <div class="chat-message" v-for="message in messages">
        <p class="title is-6">{{ message.user.name }}</p>
        <p>{{ message.message }}</p>           
    </div>
</div>

Javascript (pure):

const messages = document.getElementById('messages');

function getMessages() {
    // Prior to getting your messages.
    shouldScroll = messages.scrollTop + messages.clientHeight === messages.scrollHeight;

    // After getting your messages.
    if (!shouldScroll) {
        scrollToBottom();
    }
}

function scrollToBottom() {
    messages.scrollTop = messages.scrollHeight;
}

scrollToBottom();

setInterval(getMessages, 100);

Encountering this error message in the console:

Uncaught TypeError: Cannot read property 'scrollHeight' of null

UPDATE1. Resolved by adjusting script order after vuejs

UPDATE2. How can I disable this auto-scroll feature when the user is manually scrolling?

Answer №1

Ensure that you invoke the function following #messages:

window.onload = function(){
  setTimeout(fetchNewMessages, 150);
};

Answer №2

The problem was caused by the arrangement of included scripts; the div element must be present before vuejs is loaded.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Jest - Silence greets the test results

Struggling with Jest has been a common theme for me ever since I first attempted to use it. Regardless of the tests I run or the options I try to pass to Jest, I never seem to get the expected 'Pass' or 'Fail' results in the console. In ...

Unable to display the current state after update in React Native

I am facing an issue where I cannot display the updated state name in the sidedrawer of my app. Even though my functions are working fine and I can see the name printed twice in the console, the actual name value is not showing up on the app screen - it ...

What is the method for attaching a variable to a jQuery AJAX call?

Here's the scenario explained: while (...) { var dynamicString = 'something that varies with each ajax request.'; $.ajax({'type': 'GET','dataType': 'json', 'url': 'get_data.php& ...

How can you connect a jQuery UI sortable component to an array?

Is there a way to connect a jQuery UI sortable element with an array in order to assign an index to each sortable element within the array? I am looking for a method to automatically sort the array based on the movement of the sortable elements. Any sugg ...

Numerous issues encountered in a sample ReactJS project

I am encountering the following errors: bundle.js:1079 Warning: render(): Rendering components directly into document.body is discouraged, since its children are often manipulated by third-party scripts and browser extensions. This may lead to subtle reco ...

Tips for executing a series of tasks before a node js process is terminated

Dealing with signal from an external file in a JavaScript file. I have a shell script that stops all running processes. When my node process is stopped or killed, I need to perform a specific task before allowing the node to stop/killed. In my JavaScript ...

What is the best way to invoke functions with input of type 'number'?

As someone new to HTML, I have an input field with type=number: <input type="number" min="1" value="1" id="amount-input" (click)="chooseStanding(standingspot.priceCategory)"> When the (click) event i ...

Discovering ways to determine if multiple strings are present within a single string using JavaScript

After writing this function, I noticed it only worked with a single string value. contains(input, words) { let input1 = input.split(' '); for (var i = 0; i < input1.length; i++) { if (input1[i] === words) { ...

Shadow typing, also known as type over words, is a method where the

I am currently tackling a project focused on language acquisition, including German, Chinese, and more. We are encountering difficulties with one specific feature - the ability to display "ghost" text (in a very faint grey) for users to type over. With th ...

Implementing model synchronization on server initialization with Next.js and sequelize

When it comes to using Express with React on the backend, I'm accustomed to working in a server.js file to synchronize the database. However, I've recently started working with Next.js and noticed that there's no server.js file to sync the m ...

Should the button be disabled when the final color is in view?

I'm attempting to prevent the next button from being active when the last div is visible or has the class "activeNavLi". However, the code provided isn't achieving this - instead, it's removing and adding classes to different eleme ...

Enhance Your AngularJS Application with Data Transfer Object Models

Is there a way to implement a Data Transfer Object (DTO)? In my backend code, I have clearly defined domains such as the Client class: class Client { protected $firstName; protected $lastName; } This class contains specific properties that I wan ...

Can you provide some guidance on accessing HTTP headers while using Promises to make AJAX requests?

Currently, I am working on resolving jQuery ajax requests using bluebird.js and I have found it quite challenging to access the HTTP headers of the request. Here is a snippet of the code I am working with: Promise.resolve($.get(...)).then(function(data){ ...

Modifying elements within a JSON array-generated list

As a beginner in JavaScript, I have encountered an issue with my code. It dynamically creates a list from a JSON array called rolesData and displays the data from "roles" in a list based on a random selection (using document.body.appendChild(createList(rol ...

What is the best way to set up localStorage with a multi-dimensional array

I am struggling with modifying my local storage and it's taking up a lot of my time. Initially, I set it up like this: localStorage.setItem('example','{"data": []}'); It was working fine, but now I need to structure it like the ...

Guide to specifying the dimensions of a bar chart on Android devices

I'm currently using phonegap for my app development and incorporating flot to generate charts. Below is the snippet of my JavaScript code: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <scrip ...

Unable to properly call a JavaScript file from an HTML file

Executing this simple code with the JavaScript line placed under Script tags will trigger the desired alert message: <!DOCTYPE html> <!-- saved from url=(0014)about:internet --> <html> <body> <script type="text/javascript" > ...

Struggling to delete a specific item by its ID from MongoDB within a Next.js application

Currently, I am building a todo app in nextjs to enhance my skills. However, I'm encountering some difficulties in deleting single todos from the database using the deleteOne function. Below is the frontend call: async function deleteTodo(id) { a ...

Creating a Unique Flot Bar Chart Experience

I am currently working on creating a bar chart and have the following requirements: Bar labels for each data point Centering the bars in the grid Below is my jQuery code snippet: var data = [[0,206],[1,118],[2,37]]; var dataset = [ { labe ...

Tips for creating an option list on the fly

In need of help here! I have a dropdown list that needs to be dynamically populated using jQuery because the list contents are constantly changing. I initially got the code inspiration from a website, but it was built with a fixed number of items in mind. ...