Show / hide div overflow on anchor
I am trying to make a div, if not already visible, and scroll to a specific anchor. I found this answer and will try to use it, but it doesn't seem to work ...
My code: http://jsfiddle.net/0sq2rfcx/9/
As you can see when you click on the button it scrolls to the anchor, but if you click again it will move to a different position ... I would like it to stay at the current anchor if you keep clicking on the button.
Can you help me find what I did wrong plz?
$('#b1').click(function() {
$('#result').show();
$('#result').scrollTop($('#a1').offset().top);
});
$('#b2').click(function() {
$('#result').show();
$('#result').scrollTop($('#a2').offset().top);
});
$('#b3').click(function() {
$('#result').show();
$('#result').scrollTop($('#a3').offset().top);
});
#result {
display: none;
height: 200px;
overflow-y: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<button id='b1'>b1</button>
<button id='b2'>b2</button>
<button id='b3'>b3</button>
<button onclick="$('#result').hide();">hide</button>
<div id='result'>
<p>bla 0</p>
<br/>
<br/>
<br/>
<br/>
<br/>
<p id='a1'>bla 1</p>
<br/>
<br/>
<br/>
<br/>
<br/>
<p id='a2'>bla 2</p>
<br/>
<br/>
<br/>
<br/>
<br/>
<p id='a3'>bla 3</p>
<br/>
<br/>
<br/>
<br/>
<br/>
</div>
+3
source to share
2 answers
I just updated your jsfiddle: http://jsfiddle.net/0sq2rfcx/8/
This should work on all browsers included IE7
$('#b1').click(function () {
$('#result').show();
$("#result").animate({ scrollTop:$('#a1').parent().scrollTop() + $('#a1').offset().top - $('#a1').parent().offset().top}, "slow");
});
$('#b2').click(function () {
$('#result').show();
$("#result").animate({ scrollTop:$('#a2').parent().scrollTop() + $('#a2').offset().top - $('#a2').parent().offset().top}, "slow");
});
$('#b3').click(function () {
$('#result').show();
$("#result").animate({ scrollTop:$('#a3').parent().scrollTop() + $('#a3').offset().top - $('#a3').parent().offset().top}, "slow");
+2
source to share