Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to scroll to top of a div using jQuery?

I have a gridview inside a div.. I want to scroll to top of the div from the bottom of the div using jquery.. Any suggestion..

<div id="GridDiv"> // gridview inside.. </div> 

My gridview will have custom pagination generated link buttons in it... I will scroll to top of the div from the bottom of the link button click ...

protected void Nav_OnClick(object sender, CommandEventArgs e)     {         LinkButton lb1 = (LinkButton)sender;         //string s = lb1.ID;         ScriptManager.RegisterClientScriptBlock(lb1, typeof(LinkButton),   "scroll", "javascript:document.getElementById('GridDiv').scrollTop = 0;", true); 

In the place of javascript, I ll call the jquery function... Any suggestion...

EDIT:

Exactly like Stackoverflow questions per user page... When changing page nos it scrolls to top with smooth effect... I want to achieve that...

like image 513
ACP Avatar asked Mar 03 '10 05:03

ACP


People also ask

How do I scroll to the top of a div?

Use the scrollTo() Method to Scroll to Top of Div in JavaScript. The scrollTo() method takes parameters to reset the viewport measurements. Usually, the current state of the viewport will have its position on the x-axis and y-axis.

What is jQuery scrollTop?

jQuery scrollTop() Method The scrollTop() method sets or returns the vertical scrollbar position for the selected elements. Tip: When the scrollbar is on the top, the position is 0. When used to return the position: This method returns the vertical position of the scrollbar for the FIRST matched element.

How do I change the scroll position to top in CSS?

If you want to set the scroll position of document. body , you can scroll the entire window altogether using window. scrollTo() ; it takes either a pair of coordinates (x,y) or an options object – if you just want to scroll nicely to the top, try window. scrollTo({top:0,behavior:'smooth'}); .


2 Answers

Here is what you can do using jquery:

$('#A_ID').click(function (e) { //#A_ID is an example. Use the id of your Anchor     $('html, body').animate({         scrollTop: $('#DIV_ID').offset().top - 20 //#DIV_ID is an example. Use the id of your destination on the page     }, 'slow'); }); 
like image 142
Greg Mathews Avatar answered Sep 20 '22 20:09

Greg Mathews


Or, for less code, inside your click you place:

setTimeout(function(){   $('#DIV_ID').scrollTop(0);  }, 500); 
like image 30
M.Bush Avatar answered Sep 24 '22 20:09

M.Bush