Reputation: 1635
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?
Upvotes: 19
Views: 45397
Reputation: 13597
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');
Upvotes: 50
Reputation: 459
OVERKILL!!! Using scrollTop, or jquery for that matter... for such a simple task may not be advisable. Use anchors instead:
<a name="pageTop"></a>
....
<a href="#pageTop">TOP</a>
Or is there something more you want to do / achieve?
Upvotes: 0
Reputation: 29739
You do not need jQuery (or even JavaScript) for this.
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>
Upvotes: 5
Reputation: 3091
Use ScrollTop if you are dealing with a y-overflow and/or ScrollLeft for x-overflow.
$('#yourbuttonid').click(function() {
$('#First').scrollTop(0);//for vertical scroll
$('#First').scrollLeft(0);//for horizontal scroll
});
Upvotes: 1
Reputation: 2832
$('#scrollToTopButton').click(function(){
$('#First').scrollTop(0);
});
Upvotes: 1