- Windows scroll to element
- 1. Плавный скролл с используя jQuery
- 2. Плавный скролл для всех ссылок, начинающихся с #
- 3. Плавный скролл на чистом JavaScript — метод Element.scrollIntoView()
- 4. Плавный скролл на чистом JavaScript — метод Window.scrollBy()
- How to scroll to an element in jQuery?
- 9 Answers 9
- How does this plugin solve the user experience issue
- jQuery scroll to element
- 32 Answers 32
- How to Smooth Scroll to an Element with Native Javascript
- Quick Sample Code
- Customizing Scroll Behavior and Alignment with scrollIntoViewOptions Parameter
- Scroll smoothly to specific element on page
- 12 Answers 12
- Super smoothly with requestAnimationFrame
- 3rd Party edit
- Smooth scrolling — look ma no jQuery
- Copyright
- Smooth scrolling with jQuery.ScrollTo
- Wiring it all up
- Fully working demo on plnkr.co
- Update May 2014
Windows scroll to element
Сначала в HTML реализуем обычный «грубый» переход к секции, а затем уже добавим jQuery для создания плавности скролла.
Добавим codeid секциям к которым мы хотим выполнять скролл, а ссылкам атрибут codehref в формате code#name . Решетка — означает идентификатор (id), а name — имя идентификатора.
Наш HTML файл получится примерно такой.
Атрибут href указывает к какому элементу необходимо осуществить переход.
1. Плавный скролл с используя jQuery
Чтобы добавить плавность перехода для необходимого элемента, просто добавьте навигации класс scrollto
Изменить скорость скролла можно поменяв значение duration
2. Плавный скролл для всех ссылок, начинающихся с #
Для этого мы обратимся к селектору атрибута тега a при помощи ^ — что будет означать, что мы выбираем все ссылки, начинающиеся с # (решётки)
3. Плавный скролл на чистом JavaScript — метод Element.scrollIntoView()
Будем использовать метод scrollIntoView(). Это стандартный нативный метод JavaScript.
У метода scrollIntoView() есть недостаток.
Если у нас будет навигация position: fixed , то нам необходимо добавить отступ сверху на x-пикселей , т.е. высоту навигации .
Для решения данной задачи отлично подойдёт метод Window.scrollBy() .
4. Плавный скролл на чистом JavaScript — метод Window.scrollBy()
Метод Window.scrollBy() имеет параметр top в котором мы укажем количество пикселей, на сколько нам необходимо прокрутить страницу.
От общей высоты документа отнимем высоту навигации и получим необходимое смещение в пикселях по оси Y .
Если нужен отступ сверху, укажите class элемента (навигации), чтобы вычислить его высоту. Если не нужен отступ, переменной topOffset присвойте значение 0 .
How to scroll to an element in jQuery?
I have done the following code in JavaScript to put focus on the particular element (branch1 is a element),
But as I am also using jQuery in my web app, so I want to do the above code in jQuery. I have tried but don’t know why its not working,
The above jquery (focus()) code is not working for div, whereas If i am trying the same code with textbox, then its working,
Please tell me, how can I put focus on a div elemnt using jQuery?
9 Answers 9
Check jQuery.ScrollTo, I think that’s the behavior that you want, check the demo.
For my problem this code worked, I had to navigate to an anchor tag on page load :
For that matter you can use this on any element, not just an anchor tag.
Like @user293153 I only just discovered this question and it didn’t seem to be answered correctly.
His answer was best. But you can also animate to the element as well.
You can extend jQuery functionalities like this:
ScrollTo is fine, but oftentimes you just want to make sure a UI element is visible, not necessarily at the top. ScrollTo doesn’t help you with this. From scrollintoview’s README:
How does this plugin solve the user experience issue
This plugin scrolls a particular element into view similar to browser built-in functionality (DOM’s scrollIntoView() function), but works differently (and arguably more user friendly):
- it only scrolls to element when element is actually out of view; if element is in view (anywhere in visible document area), no scrolling will be performed;
- it scrolls using animation effects; when scrolling is performed users know exactly they’re not redirected anywhere, but actually see that they’re simply moved somewhere else within the same page (as well as in which direction they moved);
- there’s always the smallest amount of scrolling being applied; when element is above the visible document area it will be scrolled to the top of visible area; when element is below the visible are it will be scrolled to the bottom of visible area; this is the most consistent way of scrolling — when scrolling would always be to top it sometimes couldn’t scroll an element to top when it was close to the bottom of scrollable container (thus scrolling would be unpredictable);
- when element’s size exceeds the size of visible document area its top-left corner is the one that will be scrolled to;
jQuery scroll to element
I have this input element:
Then I have some other elements, like other text inputs, textareas, etc.
When the user clicks on that input with #subject , the page should scroll to the last element of the page with a nice animation. It should be a scroll to bottom and not to top.
The last item of the page is a submit button with #submit :
The animation should not be too fast and should be fluid.
I am running the latest jQuery version. I prefer to not install any plugin but to use the default jQuery features to achieve this.
32 Answers 32
Assuming you have a button with the id button , try this example:
I got the code from the article Smoothly scroll to an element without a jQuery plugin. And I have tested it on the example below.
jQuery .scrollTo(): View — Demo, API, Source
I wrote this lightweight plugin to make page/element scrolling much easier. It’s flexible where you could pass in a target element or specified value. Perhaps this could be part of jQuery’s next official release, what do you think?
Examples Usage:
Options:
scrollTarget: A element, string, or number which indicates desired scroll position.
offsetTop: A number that defines additional spacing above scroll target.
duration: A string or number determining how long the animation will run.
easing: A string indicating which easing function to use for the transition.
complete: A function to call once the animation is complete.
How to Smooth Scroll to an Element with Native Javascript
Scrolling to an element can be achieved in Javascript using the scrollIntoView() method. Smooth animation and customizing the alignment can be set through the scrollIntoViewOptions parameter.
Quick Sample Code
NOTE : The scrollIntoView method scrolls with respect to the scrollable parent of the element. In usual cases, this means the browser window. But in cases where the element is contained within another scrollable element (element having a scrollbar), scrolling happens with respect to the parent and not the browser window.
Customizing Scroll Behavior and Alignment with scrollIntoViewOptions Parameter
The scrollIntoView method also accepts a parameter through which you can set an animated scroll behavior and also customize its alignment.
This parameter scrollIntoViewOptions is an object with the following properties :
behavior : This sets whether scrolling should be an animated one or an instant scroll to the element. It can have the following values :
- smooth : Does a smooth scrolling
- auto : Instant scrolling. This is the default value.
block : This sets the vertical alignment of the shown element with respect to the scrollable parent. It can have the following values :
- start : Element is aligned at the top of the scrollable parent. This is the default value.
- center : Element is aligned at the middle of the scrollable parent.
- end : Element is aligned at the bottom of the scrollable parent.
- nearest : This aligns the element suited to the current situation. If user is currently above the element, it will be aligned at the bottom of the scrollable parent. If user is currently below the element, it will be aligned at the top. If is is already in view, nothing will happen.
inline : This sets the horizontal alignment of the shown element with respect to the scrollable parent. It can have the following values :
- start : Element is aligned at the left of the scrollable parent.
- center : Element is aligned at the middle of the scrollable parent.
- end : Element is aligned at the right of the scrollable parent.
- nearest : Aligns the element suited to the current situation. If user is currently at the right of the element, it will be aligned at the left of the scrollable parent. If user is currently at the left of the element, it will be aligned at the right. Nothing happens if already in view. This is the default value.
Scroll smoothly to specific element on page
I want to have 4 buttons/links on the beginning of the page, and under them the content.
On the buttons I put this code:
And under links there will be content:
It is working now, but cannot make it look more smooth.
I used this code, but cannot get it to work.
Any suggestions? Thank you.
12 Answers 12
Just made this javascript only solution below.
Engine object (you can fiddle with filter, fps values):
Super smoothly with requestAnimationFrame
For smoothly rendered scrolling animation one could use window.requestAnimationFrame() which performs better with rendering than regular setTimeout() solutions.
A basic example looks like this. Function step is called for browser’s every animation frame and allows for better time management of repaints, and thus increasing performance.
For element’s Y position use functions in other answers or the one in my below-mentioned fiddle.
I set up a bit more sophisticated function with easing support and proper scrolling to bottom-most elements: https://jsfiddle.net/s61x7c4e/
Question was asked 5 years ago and I was dealing with smooth scroll and felt giving a simple solution is worth it to those who are looking for. All the answers are good but here you go a simple one.
just call the smoothScroll function on onClick event on your source element .
Note: Please check compatibility here
3rd Party edit
Support for Element.scrollIntoView() in 2020 is this:
Smooth scrolling — look ma no jQuery
Based on an article on itnewb.com i made a demo plunk to smoothly scroll without external libraries.
The javascript is quite simple. First a helper function to improve cross browser support to determine the current position.
Then a function to determine the position of the destination element — the one where we would like to scroll to.
And the core function to do the scrolling
To call it you just do the following. You create a link which points to another element by using the id as a reference for a destination anchor.
Copyright
In the footer of itnewb.com the following is written: The techniques, effects and code demonstrated in ITNewb articles may be used for any purpose without attribution (although we recommend it) (2014-01-12)
I’ve been using this for a long time:
usage: scrollToItem(element) where element is document.getElementById(‘elementid’) for example.
Variation of @tominko answer. A little smoother animation and resolved problem with infinite invoked setTimeout(), when some elements can’t allign to top of viewport.
You could also check this great Blog — with some very simple ways to achieve this 🙂
Like (from the blog)
and you can also get the element «top» position like below (or some other way)
Why not use CSS scroll-behavior property
you can use this plugin. Does exactly what you want.
You can use a for loop with window.scrollTo and setTimeout to scroll smoothly with plain Javascript. To scroll to an element with my scrollToSmoothly function: scrollToSmoothly(elem.offsetTop) (assuming elem is a DOM element).
If you want to scroll to an element by its id , you can add this function (along with the above function):
If one need to scroll to an element inside a div there is my solution based on Andrzej Sala’s answer:
Smooth scrolling with jQuery.ScrollTo
To use the jQuery ScrollTo plugin you have to do the following
- Create links where href points to another elements.id
- create the elements you want to scroll to
- reference jQuery and the scrollTo Plugin
- Make sure to add a click event handler for each link that should do smooth scrolling
Creating the links
Creating the target elements here only the first two are displayed the other headings are set up the same way. To see another example i added a link back to the navigation a.toNav
Setting the references to the scripts. Your path to the files may be different.
Wiring it all up
The code below is borrowed from jQuery easing plugin
Fully working demo on plnkr.co
You may take a look at the soucre code for the demo.
Update May 2014
Based on another question i came across another solution from kadaj. Here jQuery animate is used to scroll to an element inside a