Reputation: 3634
I want to automate a scrolling bar in a fixed div constructed with UL and LI elements. I found this suggestion $('#yourUL').scrollTop($('#yourUL li:nth-child(#)').position().top);
but it is not working for me.
<div class="download-section">
...
<div class="panel-body" style="max-height: 300px;overflow-y: scroll;">
<ul class="list-group" id="ulid">
<?php include 'myextraction.php';?>
</ul>
</div>
<script src="https://code.jquery.com/jquery-1.10.2.js">
$('#ulid').scrollTop($('#ulid li:nth-child(#)').position().top);
</script>
...
</div>
My "li"s are order by ascending date (the more recent is at the bottom). I want to automatically scrollTo the next li given the date. Eg today is 26th December, and the next event is the 31th January. Hence I want to scrollTo the li corresponding to the 31th January
https://jsfiddle.net/jojo1994/g0nmye8m/
Upvotes: 0
Views: 1318
Reputation: 569
Maybe this helps you:
for(var i=2010; i<2250; i++){
$('#ulid').append('<li id="'+i+'">'+i+'</li>');
}
function go(){
var val= 2017;
var y = prompt("Go where?", val);
$('.panel-body').scrollTop($('#ulid #'+y).position().top - 2 * $('#ulid #'+y).height());
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button onclick="go()">Go</button>
<div class="panel-body" style="max-height: 300px;overflow-y: scroll;">
<ul class="list-group" id="ulid">
</ul>
</div>
Upvotes: 1
Reputation: 8795
You were selecting ul
tag whereas your parent div
has an overflow-y
which adds scrollbar on content overflow, so change your selector from #ulid
to .panel-body
.
From
$('#ulid').scrollTop($('ul > li:nth-child(#)').position().top);
To
$('.panel-body').scrollTop($('ul > li:nth-child(2)').position().top);
$('.panel-body').scrollTop($('ul > li:nth-child(2)').position().top);
.panel-body > ul{
padding:0;
margin:0;
text-align:center;
}
.panel-body > ul > li{
padding:50px 0px;
background:yellow;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel-body" style="max-height: 300px;overflow-y: scroll;">
<ul class="list-group" id="ulid">
<li>Date - 5/12/2017</li>
<li>Date - 15/12/2017</li>
<li>Date - 23/12/2017</li>
<li>Date - 25/12/2017</li>
<li>Date - 26/12/2017</li>
</ul>
</div>
Upvotes: 1