Alexander Hein Alexander Hein - 7 months ago 6
Javascript Question

How do I scroll a active element of a list into view?

Basicially I like to make the active element always visible.

The active element in this example has the classes

option todo


How could this be done if you click on the button
scrolltoactive
with jQuery?

Thanky you,

Alex



body {
font-family: Helvetica, Arial, Sans-Serif;
}

ul.variant-scroll{
position: relative;
width: 100%;
height: 55px;
padding: 0 0 0 20px;
display: block;
float: left;
list-style: none;
counter-reset: section;
white-space: nowrap;
overflow: hidden;
overflow-x: scroll;
}

ul.variant-scroll li{
display: inline-block;
background: #f2f2f2;
color: #6056c3;
padding: 0 25px;
height: 55px;
line-height: 55px;
font-size: 1.142em;
cursor: pointer;
pointer-events: auto;
margin: 0 -4px 0 0 !important;
}

ul.variant-scroll li.todo{
background: #6056c3;
color: #fff;
cursor: default;
pointer-events: none;
}

ul.variant-scroll li.todo a{
color: #fff;
}

ul.variant-scroll li.notdone.todo,
ul.variant-scroll li.checkout{
background: #f2f2f2;
color: #525252 !important;
cursor: default;
pointer-events: none;
}

ul.variant-scroll li.notdone.todo a,
ul.variant-scroll li.checkout a{
color: #525252 !important;
}

ul.variant-scroll li::before {
counter-increment: section;
content: counter(section) ". ";
}

<button type="button" class="scrolltoactive">Scroll to active</button>

<ul class="variant-scroll">
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option">option</li>
<li class="option todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
<li class="option notdone todo">option</li>
</ul>




Answer

Here is a working fiddle.

You can use the property scrollLeft()

Like this : $('.variant-scroll').scrollLeft($('.todo').offset().left)

EDIT

If you want it to work after click on the button simply add an event listener to your button :

$('.scrolltoactive').on('click',function(){
    $('.variant-scroll').scrollLeft($('.todo').offset().left);
});
Comments