Scroll smoothly to a specific item on the page

I want to have 4 buttons / links at the top of the page, and below them is the content.

On the buttons, I put this code:

<a href="#idElement1">Scroll to element 1</a> <a href="#idElement2">Scroll to element 2</a> <a href="#idElement3">Scroll to element 3</a> <a href="#idElement4">Scroll to element 4</a> 

And the links will be the content:

 <h2 id="idElement1">Element1</h2> content.... <h2 id="idElement2">Element2</h2> content.... <h2 id="idElement3">Element3</h2> content.... <h2 id="idElement4">Element4</h2> content.... 

Now it works, but cannot make it smoother.

I used this code, but I can not get it to work.

 $('html, body').animate({ scrollTop: $("#elementID").offset().top }, 2000); 

Any suggestions? Thank.

Edit: and fiddle: http://jsfiddle.net/WxJLx/2/

+21
javascript jquery jquery-animate scroll animation
Jul 18 '13 at 11:42 on
source share
11 answers

Just made this javascript just below.

Simple use:

 EPPZScrollTo.scrollVerticalToElementById('signup_form', 20); 

Engine object (you can play with a filter, fps values):

 /** * * Created by Borbás Geri on 12/17/13 * Copyright (c) 2013 eppz! development, LLC. * * Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: * The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. * */ var EPPZScrollTo = { /** * Helpers. */ documentVerticalScrollPosition: function() { if (self.pageYOffset) return self.pageYOffset; // Firefox, Chrome, Opera, Safari. if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6 (standards mode). if (document.body.scrollTop) return document.body.scrollTop; // Internet Explorer 6, 7 and 8. return 0; // None of the above. }, viewportHeight: function() { return (document.compatMode === "CSS1Compat") ? document.documentElement.clientHeight : document.body.clientHeight; }, documentHeight: function() { return (document.height !== undefined) ? document.height : document.body.offsetHeight; }, documentMaximumScrollPosition: function() { return this.documentHeight() - this.viewportHeight(); }, elementVerticalClientPositionById: function(id) { var element = document.getElementById(id); var rectangle = element.getBoundingClientRect(); return rectangle.top; }, /** * Animation tick. */ scrollVerticalTickToPosition: function(currentPosition, targetPosition) { var filter = 0.2; var fps = 60; var difference = parseFloat(targetPosition) - parseFloat(currentPosition); // Snap, then stop if arrived. var arrived = (Math.abs(difference) <= 0.5); if (arrived) { // Apply target. scrollTo(0.0, targetPosition); return; } // Filtered position. currentPosition = (parseFloat(currentPosition) * (1.0 - filter)) + (parseFloat(targetPosition) * filter); // Apply target. scrollTo(0.0, Math.round(currentPosition)); // Schedule next tick. setTimeout("EPPZScrollTo.scrollVerticalTickToPosition("+currentPosition+", "+targetPosition+")", (1000 / fps)); }, /** * For public use. * * @param id The id of the element to scroll to. * @param padding Top padding to apply above element. */ scrollVerticalToElementById: function(id, padding) { var element = document.getElementById(id); if (element == null) { console.warn('Cannot find element with id \''+id+'\'.'); return; } var targetPosition = this.documentVerticalScrollPosition() + this.elementVerticalClientPositionById(id) - padding; var currentPosition = this.documentVerticalScrollPosition(); // Clamp. var maximumScrollPosition = this.documentMaximumScrollPosition(); if (targetPosition > maximumScrollPosition) targetPosition = maximumScrollPosition; // Start animation. this.scrollVerticalTickToPosition(currentPosition, targetPosition); } }; 
+23
Dec 18 '13 at 23:30
source share

Super seamlessly with requestAnimationFrame

To smoothly render scrolling animations, you can use window.requestAnimationFrame() which works better when rendering than the usual setTimeout() solutions.

The main example is as follows. step function is called for the browser for each frame of the animation and allows you to better control the redrawing and, thus, improve performance.

 function doScrolling(elementY, duration) { var startingY = window.pageYOffset; var diff = elementY - startingY; var start; // Bootstrap our animation - it will get called right before next frame shall be rendered. window.requestAnimationFrame(function step(timestamp) { if (!start) start = timestamp; // Elapsed milliseconds since start of scrolling. var time = timestamp - start; // Get percent of completion in range [0, 1]. var percent = Math.min(time / duration, 1); window.scrollTo(0, startingY + diff * percent); // Proceed with animation as long as we wanted it to. if (time < duration) { window.requestAnimationFrame(step); } }) } 

To position the element Y, use the functions in the other answers or those given in my fiddle below.

I set up a slightly more complex function with simplified support and proper scrolling to the very bottom elements: https://jsfiddle.net/s61x7c4e/

+58
Sep 14 '16 at 15:25
source share

Smooth scrolling - see ma no jQuery

Based on an article on itnewb.com, I made a demo plan for smooth scrolling without external libraries.

javascript is pretty simple. First, a helper function to improve cross-browser support for determining the current position.

 function currentYPosition() { // Firefox, Chrome, Opera, Safari if (self.pageYOffset) return self.pageYOffset; // Internet Explorer 6 - standards mode if (document.documentElement && document.documentElement.scrollTop) return document.documentElement.scrollTop; // Internet Explorer 6, 7 and 8 if (document.body.scrollTop) return document.body.scrollTop; return 0; } 

Then the function to determine the position of the target element - the one where we would like to scroll.

 function elmYPosition(eID) { var elm = document.getElementById(eID); var y = elm.offsetTop; var node = elm; while (node.offsetParent && node.offsetParent != document.body) { node = node.offsetParent; y += node.offsetTop; } return y; } 

And the main function to scroll

 function smoothScroll(eID) { var startY = currentYPosition(); var stopY = elmYPosition(eID); var distance = stopY > startY ? stopY - startY : startY - stopY; if (distance < 100) { scrollTo(0, stopY); return; } var speed = Math.round(distance / 100); if (speed >= 20) speed = 20; var step = Math.round(distance / 25); var leapY = stopY > startY ? startY + step : startY - step; var timer = 0; if (stopY > startY) { for ( var i=startY; i<stopY; i+=step ) { setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); leapY += step; if (leapY > stopY) leapY = stopY; timer++; } return; } for ( var i=startY; i>stopY; i-=step ) { setTimeout("window.scrollTo(0, "+leapY+")", timer * speed); leapY -= step; if (leapY < stopY) leapY = stopY; timer++; } return false; } 

To call it, you simply do the following. You create a link pointing to another element, using the identifier as the link to link to.

 <a href="#anchor-2" onclick="smoothScroll('anchor-2');">smooth scroll to the headline with id anchor-2<a/> ... ... some content ... <h2 id="anchor-2">Anchor 2</h2> 

Copyright

The itnewb.com footer says: The techniques, effects and code demonstrated in ITNewb articles may be used for any purpose without attribution (although we recommend it) (2014-01-12)

+16
Jul 18 '13 at 18:58
source share

I have been using this for a long time:

 function scrollToItem(item) { var diff=(item.offsetTop-window.scrollY)/8 if (Math.abs(diff)>1) { window.scrollTo(0, (window.scrollY+diff)) clearTimeout(window._TO) window._TO=setTimeout(scrollToItem, 30, item) } else { window.scrollTo(0, item.offsetTop) } } 

usage: scrollToItem(element) where element is document.getElementById('elementid') , for example.

+4
Jul 05 '16 at 14:44
source share

Change @ tominko answer. A bit smoother animation and resolved issue with endless called setTimeout () when some elements cannot be anchored to the top of the viewport.

 function scrollToItem(item) { var diff=(item.offsetTop-window.scrollY)/20; if(!window._lastDiff){ window._lastDiff = 0; } console.log('test') if (Math.abs(diff)>2) { window.scrollTo(0, (window.scrollY+diff)) clearTimeout(window._TO) if(diff !== window._lastDiff){ window._lastDiff = diff; window._TO=setTimeout(scrollToItem, 15, item); } } else { console.timeEnd('test'); window.scrollTo(0, item.offsetTop) } } 
+4
Nov 06 '16 at 10:15
source share

The question was asked 5 years ago, and I was dealing with smooth scroll and felt that giving a simple solution is worth the one who is looking. All the answers are good, but simple.

 function smoothScroll () { document.querySelector('.your_class or #id here').scrollIntoView({ behavior: 'smooth' }); } 

just call the smoothScroll function on the onClick event on the source element .

Note: please check compatibility here.

+3
Aug 13 '18 at 6:40
source share

you can use this plugin. What exactly do you want.

http://flesler.blogspot.com/2007/10/jqueryscrollto.html

+2
Jul 18 '13 at 11:48 on
source share

If you need to scroll to an element inside a div element, my solution is based on the answer of Andrzej Sala :

 function scroolTo(element, duration) { if (!duration) { duration = 700; } if (!element.offsetParent) { element.scrollTo(); } var startingTop = element.offsetParent.scrollTop; var elementTop = element.offsetTop; var dist = elementTop - startingTop; var start; window.requestAnimationFrame(function step(timestamp) { if (!start) start = timestamp; var time = timestamp - start; var percent = Math.min(time / duration, 1); element.offsetParent.scrollTo(0, startingTop + dist * percent); // Proceed with animation as long as we wanted it to. if (time < duration) { window.requestAnimationFrame(step); } }) } 
0
Jun 25 '18 at 17:54
source share

You can use the for loop with window.scrollTo and setTimeout to smoothly scroll with simple Javascript. To jump to an element using my scrollToSmoothly function: scrollToSmoothly(elem.offsetTop) (assuming elem is a DOM element).

 function scrollToSmoothly(pos, time){ /*Time is only applicable for scrolling upwards*/ /*Code written by hev1*/ /*pos is the y-position to scroll to (in pixels)*/ if(isNaN(pos)){ throw "Position must be a number"; } if(pos<0){ throw "Position can not be negative"; } var currentPos = window.scrollY||window.screenTop; if(currentPos<pos){ var t = 10; for(let i = currentPos; i <= pos; i+=10){ t+=10; setTimeout(function(){ window.scrollTo(0, i); }, t/2); } } else { time = time || 2; var i = currentPos; var x; x = setInterval(function(){ window.scrollTo(0, i); i -= 10; if(i<=pos){ clearInterval(x); } }, time); } } 

If you want to scroll an element by its id , you can add this function (along with the above function):

 function scrollSmoothlyToElementById(id){ var elem = document.getElementById(id); scrollToSmoothly(elem.offsetTop); } 

Demo version:

 <button onClick="scrollToDiv()">Scroll To Element</button> <div style="margin: 1000px 0px; text-align: center;">Div element<p/> <button onClick="scrollToSmoothly(Number(0))">Scroll back to top</button> </div> <script> function scrollToSmoothly(pos, time){ /*Time is only applicable for scrolling upwards*/ /*Code written by hev1*/ /*pos is the y-position to scroll to (in pixels)*/ if(isNaN(pos)){ throw "Position must be a number"; } if(pos<0){ throw "Position can not be negative"; } var currentPos = window.scrollY||window.screenTop; if(currentPos<pos){ var t = 10; for(let i = currentPos; i <= pos; i+=10){ t+=10; setTimeout(function(){ window.scrollTo(0, i); }, t/2); } } else { time = time || 2; var i = currentPos; var x; x = setInterval(function(){ window.scrollTo(0, i); i -= 10; if(i<=pos){ clearInterval(x); } }, time); } } function scrollToDiv(){ var elem = document.querySelector("div"); scrollToSmoothly(elem.offsetTop); } </script> 
0
Aug 04 '18 at 20:42
source share

You can also check out this wonderful blog - with some very simple ways to achieve this :)

https://css-tricks.com/snippets/jquery/smooth-scrolling/

0
May 16 '19 at 8:51
source share

Smooth scrolling with jQuery.ScrollTo

To use the jQuery ScrollTo plugin, you must do the following

  • Create links where href points to other elements.
  • create the elements you want to scroll to
  • jQuery reference and scrollTo plugin
  • Be sure to add a click event handler for each link that should smooth the scroll.

Link Building

 <h1>Smooth Scrolling with the jQuery Plugin .scrollTo</h1> <div id="nav-list"> <a href="#idElement1">Scroll to element 1</a> <a href="#idElement2">Scroll to element 2</a> <a href="#idElement3">Scroll to element 3</a> <a href="#idElement4">Scroll to element 4</a> </div> 

Creating target elements, only the first two are displayed here, the other headers are configured the same. To see another example, I added a.toNav navigation a.toNav

 <h2 id="idElement1">Element1</h2> .... <h2 id="idElement1">Element1</h2> ... <a class="toNav" href="#nav-list">Scroll to Nav-List</a> 

Setting up links to scripts. Your file path may be different.

 <script src="./jquery-1.8.3.min.js"></script> <script src="./jquery.scrollTo-1.4.3.1-min.js"></script> 

Posting everything

The code below is borrowed from jQuery easing plugin

 jQuery(function ($) { $.easing.elasout = function (x, t, b, c, d) { var s = 1.70158; var p = 0; var a = c; if (t == 0) return b; if ((t /= d) == 1) return b + c; if (!p) p = d * .3; if (a < Math.abs(c)) { a = c; var s = p / 4; } else var s = p / (2 * Math.PI) * Math.asin(c / a); // line breaks added to avoid scroll bar return a * Math.pow(2, -10 * t) * Math.sin((t * d - s) * (2 * Math.PI) / p) + c + b; }; // important reset all scrollable panes to (0,0) $('div.pane').scrollTo(0); $.scrollTo(0); // Reset the screen to (0,0) // adding a click handler for each link // within the div with the id nav-list $('#nav-list a').click(function () { $.scrollTo(this.hash, 1500, { easing: 'elasout' }); return false; }); // adding a click handler for the link at the bottom $('a.toNav').click(function () { var scrollTargetId = this.hash; $.scrollTo(scrollTargetId, 1500, { easing: 'elasout' }); return false; }); }); 

Fully working demo at plnkr.co

You can take a look at the sub code for a demo.

Upgrade to 2014

On another issue, I came across another solution from kadaj . Here jQuery aimate is used to scroll to an element inside <div style=overflow-y: scroll>

  $(document).ready(function () { $('.navSection').on('click', function (e) { debugger; var elemId = ""; //eg: #nav2 switch (e.target.id) { case "nav1": elemId = "#s1"; break; case "nav2": elemId = "#s2"; break; case "nav3": elemId = "#s3"; break; case "nav4": elemId = "#s4"; break; } $('.content').animate({ scrollTop: $(elemId).parent().scrollTop() + $(elemId).offset().top - $(elemId).parent().offset().top }, { duration: 1000, specialEasing: { width: 'linear' , height: 'easeOutBounce' }, complete: function (e) { //console.log("animation completed"); } }); e.preventDefault(); }); }); 
-2
Jul 19 '13 at 9:01
source share



All Articles