scroll the element to the top of page jquery

I was needed some functionality ,
where i can scroll the content to top of the page.
I am having many divs which are hidden , and its headings only shown.
I want that on click of that heading , div should open up and should scroll to top.
So here is the function which can help you.

Special Thanks : Anand Dhungav.

function auto_scroll(obj){
   // alert($(obj).html());
    if($(obj).text() != ""){
        var x = Math.round( $(obj).offset().left );
        var y = ( Math.round( $(obj).offset().top))-30;
         var y = (Math.round($(obj).offset().top))-10;
        $('html, body').animate({scrollTop:y},500);



On Dom Ready or inside some function .

you can use.

//calling function

//assume that div is your element and you are passing its id to some

E.G :
say you have.

<a id="a_1" onclick="pk(">1</a>
<div id="div_1">

<a id="a_2" onclick="pk(">2</a>
<div id="div_2">

<a id="a_3" onclick="pk(">3</a>
<div id="div_3">

SO here on Click of <a> tag , you can call some function ,
explode the number/digit from its id , and then you can pass ,
it to a function.

here 'id' is <div> id and relevant <a> id.
function pk(id1){

id1 = id1.split('_');

id = id1[1]; 
// number digit to get id of clicked <a> and to set it for <div>
auto_scroll($("#div_"+id)); //this will do your task


Share on Facebook

One thought on “scroll the element to the top of page jquery”