- .scroll To ( )
- Как пишется
- Как понять
- На практике
- Дока Дог советует
- Scroll to Bottom of a Div in JavaScript
- Use scrollTop and scrollHeight to Scroll to the Bottom of Div in JavaScript
- Use jQuery to Scroll to the Bottom of Div in JavaScript
- Use jQuery .animate() to Scroll to Bottom of Div in JavaScript
- Use element.scroll() to Scroll to Bottom of Div in JavaScript
- Use element.scrollintoview() to Scroll to Bottom of Div in JavaScript
- Related Article — JavaScript Div
- Related Article — JavaScript Scroll
.scroll To ( )
Метод scroll To ( ) позволяет программно прокрутить элемент до некоторой точки координат на странице.
Как пишется
Скопировать ссылку «Как пишется» Скопировано
window.scrollTo(x, y)
window.scrollTo(x, y)
Где x и y — это координаты левого верхнего угла экрана.
Для скролла внутри элемента (например, в ) нужно сначала получить этот элемент. Прокрутим первый на странице на 100 пикселей вниз (этот блок должен содержать достаточно контента, чтобы появился скроллбар):
const div = document.querySelector('div') div.scrollTo(0, 100)
const div = document.querySelector('div') div.scrollTo(0, 100)
Вместо координат в scroll To ( ) можно передать объект с тремя параметрами:
- top задаёт количество пикселей для прокрутки по оси Y;
- left то же самое, но по оси X;
- behavior определяет поведение прокрутки. По умолчанию резкое auto , но можно указать плавный smooth .
window.scrollTo( top: 100, left: 0, behavior: 'smooth'>)
window.scrollTo( top: 100, left: 0, behavior: 'smooth' >)
Как понять
Скопировать ссылку «Как понять» Скопировано
scroll To ( ) необходим в случае, когда прокрутку нужно совершить до определённых координат на экране. В случае прокрутки относительно текущего положения лучше воспользоваться scroll By ( ) , а в случае прокрутки до конкретного элемента — методом scroll Into View ( ) .
На практике
Скопировать ссылку «На практике» Скопировано
Дока Дог советует
Скопировать ссылку «Дока Дог советует» Скопировано
🛠 Прокрутка на определённые координаты полезна, когда вёрстка страницы или элемента одинакова. Это сложно гарантировать в реальном мире, где сайт пытается адаптироваться под разрешение экрана каждого пользователя. Но рассмотрим пример из идеальной вселенной:
Во вселенной, где адаптивный дизайн используется везде — используют scroll By ( ) или scroll Into View ( ) 😎
Scroll to Bottom of a Div in JavaScript
- Use scrollTop and scrollHeight to Scroll to the Bottom of Div in JavaScript
- Use jQuery to Scroll to the Bottom of Div in JavaScript
- Use jQuery .animate() to Scroll to Bottom of Div in JavaScript
- Use element.scroll() to Scroll to Bottom of Div in JavaScript
- 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.
- Scroll to bottom with scrollTop and scrollHeight .
- Scroll to bottom with jQuery.
- Scroll to bottom with jQuery .animate() .
- Scroll to bottom with Element.scroll() .
- 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.
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.
- Get the element’s ID using the jQuery selector.
- Attach the .animate() API to this element.
- Pass an object as the first argument of the .animate() API. In this object, do the following:
- Create an object property whose name is scrollTop .
- 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