Melissa Melissa - 5 months ago 24
jQuery Question

scroll to top inside a scrollable div

I have many sections inside a scrollable div, I'm trying to animate the section to top if clicked, it works good the first time but not after that. this is my 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>




Answer

You need to add the .test's current scrollTop() position to your math

$(".test").on("click", "p", function(evt) {

  var $test = $(evt.delegateTarget), // The ".test" parent element
      $p    = $(this);               // The 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>

Comments