4lackof 4lackof - 3 months ago 19
Javascript Question

JS/jQuery - set scroll bar of side nav bar to certain position

I have a side nav bar which looks like this:



.scroll-box {
overflow: hidden;
width: 128px;
}
.filler {
height: 256px;
overflow-y: auto;
}
.selector {
background-color: #369;
padding: 8px 4px;
text-align: center;
flex-grow: 1;
display: inline-block;
cursor: pointer;
box-sizing: border-box;
transition: .1s !important;
}
.bar {
height: 8px;
width: 100%;
background-color: #808080;
}
.label {
padding: 4px 8px;
background-color: #707070;
}
.active {
background-color: lightgrey;
color: #369;
}

<div class="scroll-box">
<div class="label">Dates</div>
<div class="filler">
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector active" id="today">15-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
<div class="selector">4-Aug-16</div>
</div>
<div class="bar"></div>
</div>





I want to get it so that when the page loads, it automatically centers the view of the side nav bar to the
today
id element. I've tried putting
myUrl#today
but that changes the entire page scroll, which I do not want. I

I only want the scroll in the side nav bar to change it's position and center on the
#today
bit.
Does anyone know of a way to do this?

I am willing to use jQuery and JS as well.

Thank you.

Answer

I think you can use jQuery code such as

$(document).ready(function(){
  if($('#today').length > 0){
    var distance_to_top = $('#today').offset().top;
    var top_label_height = $('.label').height();
    var distance_to_scroll = distance_to_top - top_label_height - 8; //8 px is body margin on jsfiddle
    $('.filler').scrollTop(distance_to_scroll);
  }
});

find the offset of the today element relative to its parent, then minus the label height because the label will cover on top of the #today. the scroll to top

The demo can be found at here