Ways to move the scroll to the bottom of the div by clicking

Can anyone help with why my scroll code isn't working? I'm trying to make the scroll go to the bottom when I click on $('#openDiv').

For example, when you enter a chat room on stackoverflow, the scroll is automatically at the bottom, and that's what I want.

I've also attempted putting the scroll code outside of the click function, but it's still not functioning...

$(document).ready(function() {

  $('#openDiv').on('click', function(){
    $('#openDiv').hide();
    $('#closeDiv').show();
    
    ///////// NOT WORKING /////////
    $("#mainDiv").animate({
      scrollTop: $('#mainDiv').prop("scrollHeight")
    }, 1000);
    ///////// NOT WORKING /////////
    
    $("#mainDiv").show();
  });
  
  $('#closeDiv').on('click', function(){
    $('#closeDiv').hide();
    $("#mainDiv").hide();
    $('#openDiv').show();
  });
  
});
#mainDiv {
  height: 150px;
  background-color: #2A2A2A;
  overflow-y: auto;
  overflow-x: hidden;
  display: none;
}

#divText {
  color: #fff;
  background-color: #555555;
  height: 20px;
}
#divTextEnd{
  color: #fff;
  background-color: red;
  height: 20px;
}

#openDiv{
  background-color: green;
  border: none;
  color: #fff;
}

#closeDiv{
  display: none;
  background-color: red;
  border: none;
  color: #fff;
}
<button id="openDiv">Open div</button>
<button id="closeDiv">Close div</button>

<div id="mainDiv">

  <div id="divText">
    <h5>text</h5>
  </div>
  <div id="divText">
    <h5>text</h5>
  </div>
  <div id="divText">
    <h5>text</h5>
  </div>
  <div id="divText">
    <h5>text</h5>
  </div>
  <div id="divTextEnd">
    <h5>text</h5>
  </div>

</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

Answer №1

When you make the call

$('#mainDiv').prop("scrollHeight")
, keep in mind that #mainDiv is currently hidden with display: none;. In this state, the element will have a scrollHeight value of 0.

To successfully scroll #mainDiv, first ensure it is visible:

$(document).ready(function() {

  $('#openDiv').on('click', function() {
    $('#openDiv').hide();
    $('#closeDiv').show();

    $("#mainDiv").show();

    $("#mainDiv").animate({
      scrollTop: $('#mainDiv').prop("scrollHeight")
    }, 1000);
  });

  $('#closeDiv').on('click', function() {
    $('#closeDiv').hide();
    $("#mainDiv").hide();
    $('#openDiv').show();
  });

});
#mainDiv {
  height: 150px;
  background-color: #2A2A2A;
  overflow-y: auto;
  overflow-x: hidden;
  display: none;
}

#divText {
  color: #fff;
  background-color: #555555;
  height: 20px;
}

#divTextEnd {
  color: #fff;
  background-color: red;
  height: 20px;
}

#openDiv {
  background-color: green;
  border: none;
  color: #fff;
}

#closeDiv {
  display: none;
  background-color: red;
  border: none;
  color: #fff;
}
<button id="openDiv">Open div</button>
<button id="closeDiv">Close div</button>

<div id="mainDiv">

  <div id="divText">
    <h5>text</h5>
  </div>
  <div id="divText">
    <h5>text</h5>
  </div>
  <div id="divText">
    <h5>text</h5>
  </div>
  <div id="divText">
    <h5>text</h5>
  </div>
  <div id="divTextEnd">
    <h5>text</h5>
  </div>

</div>

<script src="https://code.jquery.com/jquery-3.3.1.min.js" integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8=" crossorigin="anonymous"></script>

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

Updating Text within a Label with jQuery

Seeking assistance with a jQuery issue that I am struggling to resolve due to my limited experience. Despite attempting to search for solutions online, I have been unable to find an alternative function or determine if I am implementing the current one inc ...

What is the solution for getting `overflow-x` to function in place of `overflow-y`?

I have a main container with several sub-containers inside. When the main container's width exceeds its limit, I want to display a horizontal scroll bar. Instead of using the 'display: inline-block' property because it creates unwanted whit ...

The .val() and focus() methods are not functioning correctly

I am having an issue with a simple script: when I input a link to an image in the form's INPUT field, it should automatically display a preview of the image: https://example.com/image.jpg However, when I input the same link not by using ctrl+C/ctr ...

Styling emails in an inbox with CSS

I am developing an email application and aiming for the inbox layout to be similar to that of Mac Mail. The emails are fetched from a database using ajax, outputting to XML. I then loop through the entries to extract the necessary elements. My concern li ...

Leveraging jQuery Mobile's Pagecreate feature to interact with jQuery functions within a webpage

I'm struggling to grasp the concept of using jQuery Mobile's pagecreate feature to incorporate some jQuery functions into a page. I want the swipeleft function below to be accessible every time a page is loaded, regardless of whether it's ac ...

Having trouble retrieving information from ajax to php

I'm struggling to understand why this code is not functioning as expected: idcurso= res[0]; idusuario= res[1]; semana= res[2]; fecha=res[3]; asistencia= true; $.ajax({ type: "POST", url: '/test/7/tomarasistencia.php', data: { ...

Customizing event colors in Full Calendar

My interactive calendar is created using : $('#calendar').fullCalendar({ height: 300, //............. events: jsonData, month: firstMonth }) I am looking to dynamically change the color of an event based on certain conditions ...

Transforming the output of a PHP script from an HTML table into an ion-list format tailored for the Ionic framework

Currently I am working on an application built with the Ionic framework. I have developed a PHP file to retrieve 'Users' data from my database and it is currently being displayed in an HTML table format. In the services section of the framework, ...

What is the best way to adjust the specific scope of every element generated by ng-repeat within a directive?

Attempting to simplify tables in Angular, I am working on a directive. My goal is for the user to only need to provide the list object and the formatting of each list element in the HTML, using the my-table tag as shown below... <h3>My Table</h3& ...

Problem with Submitting Form using Search Bar

I've tried everything, but I can't seem to get this search form to submit. <div id="search_bar_container" style="z-index:99999"> <div class="container"> <form action="tour-list-search-results.php" method="post" name="searc ...

Vivaldi's performance gradually slows down as Ajax calls take longer to load before the page finally refreshes

I have a question regarding my JavaScript/jQuery application. I am making an Ajax call in the following way: var startTime = new Date().getTime(); $(target).load(url, function() { var endTime = (new Date().getTime() - startTime) / 1000; console.log(&qu ...

VueJS is preventing the closure of the modal through jQuery

Within the index.blade.php page, I have the following code snippet: <div id="books_listing" class="container"> <div class="alert alert-success" role="alert"> <p>Book suggestions has been enabled.</p> <span cl ...

CSS division nested within the center float division

In my attempt to design a 3-column home layout, I have successfully styled the center, left, and right sections. However, I am facing difficulty in placing two sliders within the middle class. My goal is to have slider1 positioned on top inside the middle ...

Persisting old select dropdown choices after failed validation with Ajax in Laravel

Within my create view, I have a dependent dropdown for "Category" and "Subcategory" that is functioning correctly. However, when certain validations fail, the selections are not restored to their previous state. Create View: <div> <label for= ...

Discovering the way to retrieve background height following a window resize using jQuery

Is there a way to obtain the background height once the window has been resized? div { background-image: url(/images/somebackground.jpg); background-size: 100% 90%; background-repeat: no-repeat; width: 70%; background-size: contain; ...

The navigation bar fails to display correctly on Internet Explorer 10

Encountering problems with IE 10. View the code here. While on the latest Chrome and Firefox, all text appears in a single line, IE displays it differently. Other modern browsers produce a different result altogether. ...

What could be causing the error when attempting to retrieve an index using the window variable?

I'm facing a strange issue where I am trying to utilize a variable that I define as follows: window.params['variable'] = { ... }; Within the function that I am using, the code looks like this: function q() { ... // for example return n ...

Using addClass and fadeIn simultaneously when hovering over an element

After writing JavaScript code that utilizes the JQuery library to swap classes on hover, I noticed that the transition between background images was quite abrupt. The code functions as intended, but I would prefer to incorporate a fadeIn and fadeOut effect ...

Implementing a jQuery function to activate a click event on an li element

I am trying to trigger a click event on a span tag when it is clicked. A list item (li) is created when the span tag is clicked to create a collection. Below are my span and ul li tags. The li list is added dynamically to the ul when the span is clicked. ...

calculation of progress bar advancement

I want to make the progress bar in my game responsive to changes in the winning score. Currently, it moves from 0% to 100%, which is equivalent to 100 points - the default winning score. But I need the progress bar to adjust accordingly based on the user-i ...