Javascript scroll element to bottom

Scroll to Bottom of a Div in JavaScript

Scroll to Bottom of a Div in JavaScript

  1. Use scrollTop and scrollHeight to Scroll to the Bottom of Div in JavaScript
  2. Use jQuery to Scroll to the Bottom of Div in JavaScript
  3. Use jQuery .animate() to Scroll to Bottom of Div in JavaScript
  4. Use element.scroll() to Scroll to Bottom of Div in JavaScript
  5. Use element.scrollintoview() to Scroll to Bottom of Div in JavaScript

This article will teach you how to scroll to the bottom of a div using the following methods.

  1. Scroll to bottom with scrollTop and scrollHeight .
  2. Scroll to bottom with jQuery.
  3. Scroll to bottom with jQuery .animate() .
  4. Scroll to bottom with Element.scroll() .
  5. Scroll to bottom with Element.scrollIntoView() .

Use scrollTop and scrollHeight to Scroll to the Bottom of Div in JavaScript

A combination of scrollTop and scrollHeight can cause an element to scroll to the bottom because scrollTop determines the number of pixels for a vertical scroll. In contrast, scrollHeight is the element’s height (visible and non-visible parts).

Therefore, for an element, when scrollTop equals scrollHeight , the browser scrolls up. This allows seeing the bottom of the element.

However, this method requires that the element should be scrollable. You can achieve this when the element has a child element that causes a vertical overflow.

Meanwhile, you can control the overflow with overflow-y: scroll . This means that without overflow-y: scroll , this method will not work.

For example, in the next code block, the HTML element with an ID of scroll-to-bottom has a height of 300 pixels. Meanwhile, the child element has a height of 400 pixels.

As a result, the child element causes an overflow in its parent element. However, we’ve controlled the overflow with overflow-y: scroll in the CSS.

head>  meta charset="utf-8">  title>Scroll to bottom - 1 (scrollTop and scrollHeight)title>  style type="text/css">  #scroll-to-bottom   border: 5px solid #1a1a1a;  padding: 2em;  width: 50%;  margin: 0 auto;  height: 300px;  overflow-y: scroll;  >  .content   height: 400px;  >   p   font-size: 100px;  >  style>  head> body>  div id="scroll-to-bottom">  div class="content">  p>This is a dummy textp>  div>  div>  script>  let scroll_to_bottom = document.getElementById('scroll-to-bottom');  scroll_to_bottom.scrollTop = scroll_to_bottom.scrollHeight;  script>  body> 

Use jQuery to Scroll to the Bottom of Div in JavaScript

jQuery defines an API called scrollTop that will get or set the vertical position of a scroll bar. The scroll bar in question will be for a set of matched elements.

When used with the element’s scrollHeight , you can scroll to the bottom of the element.

Читайте также:  background-position

We’ve selected an element with the jQuery selector in the next code. At the same time, we’ve used the element scrollTop to select the element and its scrollHeight .

You’ll note from the code that we’ve used [0] to get the DOM element. As a result, when you load the code in your web browser, the div will scroll to the bottom.

What’s more, in the JavaScript code, we’ve provided variants of this approach. However, we’ve left them as comments.

As a final note, this approach also requires that the element be scrollable.

head>  meta charset="utf-8">  title>Scroll to bottom - 2 (jQuery)title>  style type="text/css">  #scroll-to-bottom   border: 5px solid #1a1a1a;  padding: 2em;  width: 50%;  margin: 0 auto;  height: 300px;  overflow-y: scroll;  >  .content   height: 400px;  >   p   font-size: 100px;  >  style>  head> body>  div id="scroll-to-bottom">  div class="content">  p>This is a dummy textp>  div>  div>   script  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"  integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="  crossorigin="anonymous"  referrerpolicy="no-referrer"  >  script>  script>  $('#scroll-to-bottom').scrollTop($('#scroll-to-bottom')[0].scrollHeight);   // The following code do the same thing:  // $('#scroll-to-bottom').scrollTop(function()   // return this.scrollHeight;  // >);   // let scroll_to_bottom = $("#scroll-to-bottom");  // scroll_to_bottom.scrollTop(scroll_to_bottom.prop("scrollHeight"));  script>  body> 

Use jQuery .animate() to Scroll to Bottom of Div in JavaScript

The jQuery .animate() API allows you to perform custom animation on CSS properties. Therefore, you can create a smooth scroll effect.

What we mean by “smooth” is that the scroll to bottom effect will appeal to the users. However, you’ll need scrollTop and scrollHeight to pull this off.

We aim to keep the code clean because we use the .animate() API. So, we’ll wrap all our code in a function.

  1. Get the element’s ID using the jQuery selector.
  2. Attach the .animate() API to this element.
  3. Pass an object as the first argument of the .animate() API. In this object, do the following:
    1. Create an object property whose name is scrollTop .
    2. Set scrollTop value to element.prop(«scrollHeight») .

    Afterward, we call this function on the element’s HTML ID. Meanwhile, the element should be scrollable with CSS overflow-y: scroll .

    head>  meta charset="utf-8">  title>Scroll to bottom - 3 (jQuery smooth)title>  style type="text/css">  #scroll-to-bottom   border: 5px solid #1a1a1a;  padding: 2em;  width: 50%;  margin: 0 auto;  height: 300px;  overflow-y: scroll;  >  .content   height: 400px;  >   p   font-size: 100px;  >  style>  head> body>  div id="scroll-to-bottom">  div class="content">  p>This is a dummy textp>  div>  div>   script  src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"  integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ=="  crossorigin="anonymous"  referrerpolicy="no-referrer"  >  script>  script>  const smoothScroll = (id) =>   const element = $(`#$id>`);  element.stop().animate(  scrollTop: element.prop("scrollHeight")  >, 500);  >   smoothScroll('scroll-to-bottom');  script>  body> 

    Use element.scroll() to Scroll to Bottom of Div in JavaScript

    You can use element.scroll() to scroll to the bottom of an element. What element.scroll() requires is a set of coordinates.

    We’ll set the coordinates to the top of the element in this case. Also, if you’d like, you can make it a smooth scrolling.

    To scroll to the bottom with element.scroll() , set its first argument to an object. Afterward, the first property of this object should be a top property.

    This property should have a value of element.scrollHeight . Also, set the second argument of element.scroll() to behavior: «smooth» for a smooth scroll.

    We’ve used element.scroll() on the element in the following code. As a result, when you run the code in your browser, the div will scroll to the bottom.

    In addition, the element should be scrollable via CSS overflow-y: scroll .

    head>  meta charset="utf-8">  title>Scroll to bottom - 4 (Element.scroll())title>  style type="text/css">  #scroll-to-bottom   border: 5px solid #1a1a1a;  padding: 2em;  width: 50%;  margin: 0 auto;  height: 300px;  overflow-y: scroll;  >  .content   height: 400px;  >   p   font-size: 100px;  >  style>  head> body>  div id="scroll-to-bottom">  div class="content">  p>This is a dummy textp>  div>  div>   script>  let scroll_to_bottom = document.getElementById('scroll-to-bottom');  function scrollBottom(element)   element.scroll(< top: element.scrollHeight, behavior: "smooth">)  >   scrollBottom(scroll_to_bottom);  script>  body> 

    Use element.scrollintoview() to Scroll to Bottom of Div in JavaScript

    The Element.scrollIntoView() method will scroll an element to be visible to the user. As a result, you see the overflow content hidden from sight.

    At the same time, the bottom of the element.

    Unlike previous examples in this article, you’ll need a single div element. This div element should have some content.

    Also, you don’t need to set a height for the div because, with scrollIntoView , a defined height could prevent a scroll to the bottom.

    In the following code, we’ve called scrollIntoView() on the div element. Also, we’ve set its argument to false .

    This is what is required to scroll the element to the bottom.

    head>  meta charset="utf-8">  title>Scroll to bottom - 5 (scrollIntoView())title>  style type="text/css">  body   padding: 1em;  >   div   border: 5px solid #1a1a1a;  padding: 2em;  width: 50%;  margin: 0 auto;  >   p   font-size: 100px;  >  style>  head> body>  div id="scroll-to-bottom">  p>This is a dummy textp>  div>  script type="text/javascript">  let scroll_to_bottom = document.getElementById('scroll-to-bottom');  scroll_to_bottom.scrollIntoView(false);   // scroll_to_bottom.scrollIntoView(< behavior: 'smooth', block: 'end'>);  script>  body> 

    Habdul Hazeez is a technical writer with amazing research skills. He can connect the dots, and make sense of data that are scattered across different media.

    Related Article — JavaScript Div

    Related Article — JavaScript Scroll

    Copyright © 2023. All right reserved

    Источник

    Как прокрутить скролл у div до низа

    Как прокрутить скролл у div до низа

    Недавно мне надо было создать чат, и передо мной встала задача прокрутки скролла вниз у div, для того чтобы пользователь сразу увидел новое сообщение в чате. Сообщения чата, как Вы уже догадались, находились в div. Большинство программистов прокручивают скролл у div до низа неправильно, а в этой статье я покажу, как делать это с максимально чистым кодом.

    Для начала приведу HTML-код:

    Теперь продемонстрирую CSS-код, который необходим, чтобы появилась полоса прокрутки:

    div height: 100px;
    overflow: auto;
    width: 200px;
    >

    Теперь перейдём к прокрутке скролла у div. Большинство программистов делает так:

    Безусловно, данный способ рабочий. Но что если размер div огромен? Тогда полоса прокрутки уйдёт не до низа. Можно, конечно, поставить 99999999 и даже больше, но это смотрится ещё хуже. А ведь есть куда более простое и элегантное решение:

    Здесь прокрутка уйдёт до самого низа div независимо от его размеров, плюс нет констант прямо в коде, которые всегда его портят.

    И, наконец, его можно использовать не только для div, но и для самой страницы:

    Как видите, всё очень просто. Также данный способ является кроссбраузерным, поэтому можете смело его использовать.

    Создано 30.09.2013 10:43:50

  4. Михаил Русаков
  5. Копирование материалов разрешается только с указанием автора (Михаил Русаков) и индексируемой прямой ссылкой на сайт (http://myrusakov.ru)!

    Добавляйтесь ко мне в друзья ВКонтакте: http://vk.com/myrusakov.
    Если Вы хотите дать оценку мне и моей работе, то напишите её в моей группе: http://vk.com/rusakovmy.

    Если Вы не хотите пропустить новые материалы на сайте,
    то Вы можете подписаться на обновления: Подписаться на обновления

    Если у Вас остались какие-либо вопросы, либо у Вас есть желание высказаться по поводу этой статьи, то Вы можете оставить свой комментарий внизу страницы.

    Порекомендуйте эту статью друзьям:

    Если Вам понравился сайт, то разместите ссылку на него (у себя на сайте, на форуме, в контакте):

    1. Кнопка:
      Она выглядит вот так:
    2. Текстовая ссылка:
      Она выглядит вот так: Как создать свой сайт
    3. BB-код ссылки для форумов (например, можете поставить её в подписи):

    Комментарии ( 7 ):

    Михаил! А как сделать чтобы в чате если пишет человек два сообщения, то аватар извлекается только при первом сообщении а при втором сообщении будет просто пустое место?

    if (первый раз) загрузить_аватар.

    Лучше всё же не overflow: auto; а overflow-y: auto, иначе у вас может чат поехать в ширину при некоторых условиях.

    Тогда уж лучше: overflow-x: auto overflow-y: auto И вообще, overflow не действует на Chrmoe,Opera,Safari, работает только в лисе да эксплорере.

    Сделайте div большой высоты и поставьте внутрь него картинку огромной ширины, после чего откройте в хроме. Если у вас стоит overflow: auto или overflow-x: auto он будет прокручиваться как по горизонтали, так и по вертикали. Если значение auto не будет работать в вашем браузере, то overflow: scroll точно сработает. А теперь представьте, что какой-нибудь приколист засунет вам в чат картинку размером 10000×1.

    Михаил, Здравствуйте. Как можно изменить оформление полосы прокрутки — изменить ширину, использовать другой рисунок вместо «бегунка», поменять его цвет и цвет самой области прокрутки, убрать стрелки ? Спасибо.

    Максим, с помощью стилей меняются, но с последними изменениями в браузерах, это ничего не действует.

    Для добавления комментариев надо войти в систему.
    Если Вы ещё не зарегистрированы на сайте, то сначала зарегистрируйтесь.

    Copyright © 2010-2023 Русаков Михаил Юрьевич. Все права защищены.

    Источник

Оцените статью