Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scroll to top of div within a div jquery

I have a div containing several other divs, I want to be able to have which ever div is clicked to scroll to the top of the containing div.

I don't want to simply scroll to the top of the div, which would be scrollTop:0, I want whichever div is clicked for that div to scroll to the top.

Using scrollTop: $(this).offset().top only gives the offset relative to the container, so it's not correct, as it only returns a relatively small value.

Here's the setup:

    <div id="container" style="position:relative; height:400px; width:100%; overflow:auto;"> 
<div id="div1" class="clicker" style="height: 1000px; width 100px; ; background:blue">
        Test
    </div>

    <div id="div2" class="clicker" style="height: 1000px; width 100px; background:green">
        Test 2
    </div>

     <div id="div3" class="clicker" style="height: 1000px; width 100px; background:yellow">
        Test 3
    </div>

</div>

with this JS:

$(".clicker").click(function ()
                    {
                    $('#container').animate({
                        scrollTop: WHAT GOES HERE?
                    }, 2000);

            });

Here's the jsfiddle:

http://jsfiddle.net/byvL43u6/

cheers

like image 241
ojsglobal Avatar asked Dec 25 '22 23:12

ojsglobal


2 Answers

You need to combine the current scroll position of the container with the position of the div

var container = $('#container');

$(".clicker").click(function () {
    var top = $(this).position().top,
        currentScroll = container.scrollTop();

    container.animate({
        scrollTop: currentScroll + top
    }, 1000);

});

Demo at http://jsfiddle.net/ucag9dos/2


Local demo:

$(function() {
  var container = $('#container');

  $(".clicker").click(function() {
    var top = $(this).position().top,
      currentScroll = container.scrollTop();

    container.animate({
      scrollTop: currentScroll + top
    }, 1000);

  });
});
#container {
  position: relative;
  height: 400px;
  width: 100%;
  overflow: auto;
  background: red
}
.clicker {
  height: 1000px;
  width: 100%;
}
#div1 {
  background: blue
}
#div2 {
  background: green
}
#div3 {
  background: yellow
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>

<div id="container">
  <div id="div1" class="clicker">Test</div>
  <div id="div2" class="clicker">Test 2</div>
  <div id="div3" class="clicker">Test 3</div>
</div>

Another way would be to add the height of all previous siblings.

like image 198
Gabriele Petrioli Avatar answered Dec 27 '22 11:12

Gabriele Petrioli


All it neeeds to be is 0.

$(".clicker").click(function () {
    $('#container').animate({
        scrollTop: 0
    }, 2000);
});
like image 26
FluffyJack Avatar answered Dec 27 '22 12:12

FluffyJack