- Source:
Methods
scrollTo(element, durationMsopt, nullable, offsetopt, nullable, easingopt, nullable, scrollEvenIfFullyInViewportopt, nullable, cancelOnUserScrollopt, nullable) → {Basic.Deferred}
Scrolls the viewport to the element's position (first pixel at half viewport height). Does not do anything if target element is already fully in viewport, unless scrollEvenIfFullyInViewport is set to true. Uses getBoundingClientRect to measure viewport check, scrolls always if missing.
If you use this function on a window, the offset is directly used as scrollTop, so this function may also be used for things like back to top buttons.
Scrolls may be cancelled by setting cancelOnUserScroll to true, but keep in mind, that this will only work with mousewheels and (maybe) touchpads on modern browsers. No keyboard or scrollbar support yet. The root of the problem is that a user scroll is indistinguishable from a js-triggered scroll, since both trigger the scroll event and look exactly the same. So we have to use exotic and specific events like mousewheel and DOMMouseScroll. So, please, use cancelOnUserScroll only as a convenience option and not as a must.
Parameters:
Name | Type | Attributes | Default | Description |
---|---|---|---|---|
element |
HTMLElement | Window | the element to scroll to or the window to scroll within |
||
durationMs |
Number |
<optional> <nullable> |
1000 | duration of the scrolling animation |
offset |
Number |
<optional> <nullable> |
0 | offset from the viewport center to apply to the end position |
easing |
String |
<optional> <nullable> |
'easeInOutCubic' | easing function to use, can be any of Animation.EasingFunctions |
scrollEvenIfFullyInViewport |
Boolean |
<optional> <nullable> |
false | if true, forces method to always scroll no matter the element's position |
cancelOnUserScroll |
Boolean |
<optional> <nullable> |
false | if true, scrolling animation will immediately be canceled on manual user scroll, return value will not resolve in that case |
- Source:
- See:
Throws:
error if element is not usable or if durationMs is <= 0
Returns:
- Type
- Basic.Deferred
Example
document.querySelector('a.jumpitem').addEventListener('click', function(){ scrollTo(document.querySelector('.jumptarget'), function(){ alert('scrolled!'); }, 500, -100, true); });
scrollTo(document.querySelector('.jumptarget'), function(){ alert('Not triggered if user uses mousewheel.'); }, 5000, -0, false, true);
scrollTo(window, null, 500, 0, false, true);