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
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.
All it neeeds to be is 0
.
$(".clicker").click(function () {
$('#container').animate({
scrollTop: 0
}, 2000);
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With