Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery Animate Div Scroll back to top

Tags:

jquery

I have a div which has the content:

<div id="First">There are lots of content in here. Blah Blah Blah...</div>

The div has a style attribute of overflow:auto; so if any content were to overflow, a scrollbar would appear. I have a button inside the div at the end of the content.

Since the content inside the div could allow for a deep scroll, is there anyway, that on click of the button it will move the scroll back to the top of the div?

like image 680
Joe Avatar asked May 21 '12 17:05

Joe


People also ask

How to create an animated scroll to top with jQuery?

Syntax: $("html, body"). animate({ scrollTop: scrollPosition });

How to set scroll position to top using jQuery?

To set scrolltop position in jQuery, use the scrollTop() method. The scrollTop( ) method gets the scroll top offset of the first matched element. This method works for both visible and hidden elements.

How to scroll window in jQuery?

jQuery scroll() Method The scroll event works for all scrollable elements and the window object (browser window). The scroll() method triggers the scroll event, or attaches a function to run when a scroll event occurs.


2 Answers

Yes. Use scrollTop

Just provide your element and a value of 0 like this:

$('#id').scrollTop(0);

You can also animate the scrolling back to top like this:

$('#id').animate({
   scrollTop: 0
}, 'slow');
like image 66
lukas.pukenis Avatar answered Sep 25 '22 21:09

lukas.pukenis


You do not need jQuery (or even JavaScript) for this.

DEMO

Define an anchor name:

<a name="top"></a>

And create a link to this anchor at the bottom:

<a href="#top">back to top</a>​
like image 41
Alp Avatar answered Sep 21 '22 21:09

Alp