0

In the below - How can i modify my code so that when a button is clicked the scroll position changes so that button is the first. Im almost there but scrollLeft() is always zero for some reason

$('a').click( function() {
 const target = $(this).position().left;
  $('.msg').text(`Postition Left => ${target}`)
 $(".horz-scroll").scrollLeft(target)
})
.horz-scroll {
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  max-width: 100%;
  white-space: nowrap;
}

a {
  display: inline-block;
  padding: 2em;
  cursor: pointer;
  background: #000;
  color: #fff;
}

a:hover {
  background: lighten(#000,15%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="horz-scroll">
    <a>Chassis</a>
    <a>Processor</a>
    <a>Memory</a>
    <a>Controllers</a>
    <a>Hard Drives</a>
    <a>Solid State Drives</a>
    <a>FlexibleLOM Network Controller</a>
    <a>HBAs</a>
    <a>iLO Advance</a>
    <a>Network Adapters</a>
    <a>Power Suppplies</a>
    <a>Rail Kits</a>
    <a>Accessories</a>
</div>

<br>
<div class="msg"></div>
Omar
  • 2,726
  • 2
  • 32
  • 65
  • Possible duplicate of [How do I scroll to an element within an overflowed Div?](https://stackoverflow.com/questions/2346011/how-do-i-scroll-to-an-element-within-an-overflowed-div) - just change `top` to `left`. – Heretic Monkey Nov 27 '18 at 19:22

1 Answers1

0

When using arrow function ()=>{} $(this) will not refer to the target.

the calculation for the scrollable container should be currentScrollPos + .position().left of the element clicked

$('a').click( function() {
 const el = $(this).position().left;
  const currentScroll = $(".horz-scroll").scrollLeft();
  const target = el+currentScroll;
  $('.msg').text(`Postition Left => ${target}`)
 $(".horz-scroll").scrollLeft(target)
})
.horz-scroll {
  overflow-y: scroll;
  -webkit-overflow-scrolling: touch;
  max-width: 100%;
  white-space: nowrap;
}

a {
  display: inline-block;
  padding: 2em;
  cursor: pointer;
  background: #000;
  color: #fff;
}

a:hover {
  background: lighten(#000,15%);
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="horz-scroll">
    <a>Chassis</a>
    <a>Processor</a>
    <a>Memory</a>
    <a>Controllers</a>
    <a>Hard Drives</a>
    <a>Solid State Drives</a>
    <a>FlexibleLOM Network Controller</a>
    <a>HBAs</a>
    <a>iLO Advance</a>
    <a>Network Adapters</a>
    <a>Power Suppplies</a>
    <a>Rail Kits</a>
    <a>Accessories</a>
</div>

<br>
<div class="msg"></div>
Omar
  • 2,726
  • 2
  • 32
  • 65