javascript - scroll to top inside a scrollable div -


i have many sections inside scrollable div, i'm trying animate section top if clicked, works first time not after that. attempt

$('p').click (function(){  	$('.test').animate({scrolltop: $(this).offset().top}, 800);  });
.test{    overflow:auto;     max-height:300px;     width:300px;     padding-bottom:400px;  }
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div class="test">    <p>section 1</p>    <p>section 2</p>    <p>section 3</p>    <p>section 4</p>    <p>section 5</p>    <p>section 6</p>    <p>section 7</p>    <p>section 8</p>    <p>section 9</p>    <p>section 10</p>    <p>section 11</p>    <p>section 12</p>    <p>section 13</p>    <p>section 14</p>    <p>section 15</p>  </div>

you need add .test's current scrolltop() position math

$(".test").on("click", "p", function(evt) {      var $test = $(evt.delegatetarget), // ".test" parent element        $p    = $(this);               // clicked "p" element        $test.animate({      scrolltop: $p.offset().top + $test.scrolltop()    }, 800);    });
body{margin:0;}  .test{overflow:auto; height:200px; width:300px;}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>  <div class="test">    <p>section 1</p>    <p>section 2</p>    <p>section 3</p>    <p>section 4</p>    <p>section 5</p>    <p>section 6</p>    <p>section 7</p>    <p>section 8</p>    <p>section 9</p>    <p>section 10</p>    <p>section 11</p>    <p>section 12</p>    <p>section 13</p>    <p>section 14</p>    <p>section 15</p>  </div>