Melissa
Melissa

Reputation: 73

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>

Upvotes: 3

Views: 3147

Answers (1)

Roko C. Buljan
Roko C. Buljan

Reputation: 206627

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.stop().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>

Upvotes: 3

Related Questions