I'm trying to make a div appear (if not already visible) and be scrolled to a specific anchor. I found this answer and try to use it but it looks like it doesn't work well...
https://stackoverflow.com/a/7513110/3703099
My code : http://jsfiddle.net/0sq2rfcx/9/
As you can see, when you click on button it scroll to the anchor, but if you click again, it scroll to an other position... I would like to make it stay on the current anchor if you keep clicking the button.
Can you help me to 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>
I've 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");
You can use position instead to scroll
like one below:
$('#b1').click(function () {
$('#result').show();
$('#result').animate({
'scrollTop' : $("#a1").position().top-10 //-10 here is just to set it in view!!
});
});
Added animation
for smoothness
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.