Scrolling to the next wrap class in jQuery is not functioning properly with the chatbox and ScrollTop

I have created a chat box using jQuery. However, I am facing an issue where when I click the button multiple times, the scroll returns to the top. My objective is for the scroll to move to the next wrap class when the button is clicked.

Here is a snippet of my HTML:

<div class="all">
    <div class="wrap">
        <p>Hi, Please click data</p>
        <div class="data" data-content="0">data 1</div>
        <div class="data" data-content="1">data 2</div>

And here is the JavaScript portion:

var data = [
    {
        "content": `
            <p>first content</p>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
        `
    },
    {
        "content":`
            <p>second content</p>
            <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit...</p>
        `
    }
];

$(document).on('click','.data', function(){
    var datacontent = $(this).attr('data-content');
  
    $(this).parent().parent().append(`
        <div class="wrap">
            <p>${data[datacontent].content}</p>
            <div class="data" data-content="0">data 1</div>
            <div class="data" data-content="1">data 2</div>
        </div>
    `);
  
    $('.all').animate({
        scrollTop: $(this).parent().next().prop('scrollHeight')
    },100)
});

If you want to see the full code, you can view it here.

Your feedback is greatly appreciated!

Answer №1

Perhaps this solution could work for you, thank you

var items = [{
    "description": `
    <p>first item description</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam accusamus, maiores velit aut sint perspiciatis facilis. Asperiores expedita, iusto suscipit aut numquam corporis sunt sint eius dolorum ea, adipisci saepe.</p>
    `
  },
  {
    "description": `
        <p>second item description</p>
    <p>Lorem ipsum dolor sit amet, consectetur adipisicing elit. Totam accusamus, maiores velit aut sint perspiciatis facilis. Asperiores expedita, iusto suscipit aut numquam corporis sunt sint eius dolorum ea, adipisci saepe.</p>
    `
  }
];

$(document).on('click', '.item', function() {
  var itemDescription = $(this).attr('data-description');

  $('.all-items').append(`
    <div class="wrapper">
        <p>${items[itemDescription].description}</p>
        <div class="item" data-description="0">Item 1</div>
      <div class="item" data-description="1">Item 2</div>
    </div>
  `).animate({
      scrollTop: $(this).parent().next().prop('scrollHeight')
    }, 100);

});
.item {
  background:tomato;
  color:white;
  padding:8px;
  display:inline;
  cursor:pointer;
}

.all-items{
  height: 200px;
  border:1px solid;
  overflow-y:auto;
  padding:0 8px;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="all-items">
  <div class="wrapper">
    <p>
      Hi, Please click an item
    </p>
    <div class="item" data-description="0">Item 1</div>
    <div class="item" data-description="1">Item 2</div>
  </div>
</div>

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

Avoid form submission when the 'enter' key is pressed in Edge, but not in Chrome or Firefox

I'm dealing with an issue in HTML where a 'details' tag is set to open and close when the user presses enter. However, on Edge browser, pressing enter on the 'details' tag actually submits the form. I've been tasked with preve ...

Having trouble getting Google Tag Manager (GTM) to function properly on SharePoint?

I inserted the GTM code within the SharePoint Master Page body tag. <body> <--Body content goes here --> <!-- Google Tag Manager --> <noscript><iframe src="//www.googletagmanager.com/ns.html?id=GTM-XXXXXXXX" he ...

How to position ion-title at the center using position:absolute

I am a newcomer to the world of Ionic Framework. Recently, I created a page that features a swipe-back-button located on the left side of the navigation bar. This positioning causes the title to shift slightly to the right, as demonstrated by the addition ...

I am experiencing issues with local storage getItem() function not functioning properly within NUXT JS

Currently working on creating a shopping cart using nuxt js. Successfully able to store the cart data in local storage, but facing difficulty in retrieving the data. Refer to the screenshots for more details: https://i.sstatic.net/X7dL9.png https://i.sstat ...

Console frozen when executing an async JavaScript script to populate a Mongoose database

I'm currently delving into a personal project and aiming to unravel the intricate logic that is preventing my Node JS process from closing after executing populateTransactions(). My assumption is that the issue lies in not properly closing the DB con ...

What is the process for inserting images into a vertical timeline format?

I am currently working on building a timeline and incorporating images into it. I came across a solution on W3 that I'm trying to implement, but I'm facing some challenges. I've been experimenting with the code but I feel like there are part ...

I successfully corrected the selectable options list in HTML/CSS and am now working on linking it to a Django char field. I'm currently facing some difficulties in figuring out

Below is a Django form field I have defined: source_currency = forms.CharField(max_length=5) Here is an example of Select/Option HTML: <select name="fancySelect" for="{{ form.source_currency.id_for_label }}" class="makeMeFancy" id="drop1"> ...

Tips for modifying the height of a bootstrap-vue table and enabling scrolling with a fixed header

I have a div containing a b-table that I need help adjusting the height for. I want to make the table scrollable with a fixed header. Can anyone assist me? Here is my code: Code inside the template: <div class="tbl-barangay"> <b-table stripe ...

Tips for resolving the "trim" of undefined property error in Node.js

Looking to set up a basic WebAPI using Firebase cloud functions with express and TypeScript. Here's the code I have so far: import * as functions from 'firebase-functions'; import * as express from 'express'; const app = express( ...

PHP Script unable to locate results

For some reason, the script I have written is not functioning properly. Upon reviewing the code from walmart.com, I verified that name="query" is accurate. However, I am uncertain about the contents within <script></script> <html> < ...

Creating an ESNext JavaScript file and integrating it into an Angular 2 project: A comprehensive guide

I am facing an issue with my js file named UserService.js and source.js, which has been transformed using transformer typescript. My objective is to integrate this transformed js file into Angular. UserService.js import { Source } from "./source" ...

Challenges encountered when redirecting users with a combination of javascript and php

I have a login form that triggers a JavaScript function upon submission. This function calls a PHP page to process the input. The issue I'm facing is with how the redirections are displayed based on the user's role type. It attempts to display t ...

Steps to displaying the functions linked to a Jquery element

Currently diving into the realm of JQuery, I am on a quest to discover a method to access and view the associated methods of an object once it has been created, reminiscent of python's dir() function. ...

The selector-triggered JQuery event being invoked by my script

Facing an issue while trying to invoke my jQuery event. I am working with 2 jQuery events: $element.on('click', function (e) { ... }); $element.on('click', '.toggle', function (e) { ... }); My question is how can I trigge ...

Discovering the most efficient route on a looped set of items

My question may not be fully comprehensible, but essentially it involves the following scenario: I have created an interactive presentation that displays static images in a sequence to generate an animation. By clicking the Play button, the animation prog ...

A PHP tag containing a div element

As someone who is new to web development, I have a question that may seem silly to some. I am familiar with adding div tags inside php tags, but I am unsure if it's possible to add onclick functions or any other type of function to these div tags. He ...

AngularJS controller failing to update the angular variable

Currently diving into the world of angularjs, so any guidance would be greatly appreciated! I have been working on a basic angular application that compares two password strings in ng-controller and provides a brief message indicating if they match or not. ...

Guide on How to Include data (PDF Base 64) in angular 6 component

Within my Angular 6 application, I am presenting data (a report) in a new window using the following code snippet. *** The 'result' variable contains Base64 data *** if (result != null) { const pdfWindow = window.open(""); ...

Tips on reloading or refreshing a react-table component using my form component

I currently have two reactJS components set up: CustomerForm component, which includes a form along with form handling code. CustomerList component, which utilizes react-table to list the customers. Both components are fully functional and operational. ...

Trigger a click event on a dynamically loaded button

Here's a unique twist to the usual discussions on this topic. I have a dynamically loaded button in my HTML, and I've saved the selector for it. Later on in my code, I need to trigger a click event on this button programmatically. The typical $(& ...