Reputation: 9415
I want a container with vertical scroll bars to force an element to the top of the page, even if it's at the bottom of the container. This is best described through this jsfiddle:
http://jsfiddle.net/scientiffic/v7CBu/5/
I have a scrollable container ("container") that contains different elements. I can click on links on the page to force the container to scroll to the different elements in the container. However, since subcontainer "3" is at the bottom of the container, the container can't scroll such that 3 appears on the top of the page. I would like to force subcontainer 3 to be at the top. What is the best way to do this?
HTML:
<div class="container">
<div class="subcontainer 1"><h1>1</h1></div>
<div class="subcontainer 2"><h1>2</h1></div>
<div class="subcontainer 3"><h1>3</h1></div>
</div>
<div class="controllers">
<div class="controller" id="1">jump to 1</div>
<div class="controller" id="2">jump to 2</div>
<div class="controller" id="3">jump to 3</div>
</div>
Javascript:
$(document).ready(function(){
$('#1').click(function(){
$('.container').animate({
scrollTop: $('.subcontainer.1').position().top + $('.container').scrollTop()
}, 500);
});
$('#2').click(function(){
console.log('go to 2');
$('.container').animate({
scrollTop: $('.subcontainer.2').position().top + $('.container').scrollTop()
}, 500);
});
$('#3').click(function(){
console.log('go to 3');
$('.container').animate({
scrollTop: $('.subcontainer.3').position().top + $('.container').scrollTop()
}, 500);
});
});
Upvotes: 1
Views: 710
Reputation: 4057
You could add a shim below, and change it's height depending on what is being clicked. A bit of a hack, but it works:
HTML:
<div class="container">
<div class="subcontainer 1">
<h1>1</h1>
</div>
<div class="subcontainer 2">
<h1>2</h1>
</div>
<div class="subcontainer 3">
<h1>3</h1>
</div>
<div class="shim"></div>
</div>
<div class="controllers">
<div class="controller" id="1">go to 1</div>
<div class="controller" id="2">go to 2</div>
<div class="controller" id="3">go to 3</div>
</div>
JS:
$(document).ready(function () {
$('#1').click(function () {
$('.shim').height(0);
$('.container').animate({
scrollTop: $('.subcontainer.1').position().top + $('.container').scrollTop()
}, 1000);
});
$('#2').click(function () {
console.log('go to 2');
$('.shim').height(0);
$('.container').animate({
scrollTop: $('.subcontainer.2').position().top + $('.container').scrollTop()
}, 1000);
});
$('#3').click(function () {
console.log('go to 3');
var newHeight = $('.container').height() - $('.subcontainer.3').outerHeight();
$('.shim').height(newHeight);
$('.container').animate({
scrollTop: $('.subcontainer.3').position().top + $('.container').scrollTop()
}, 1000);
});
});
Upvotes: 1