3

I have a div which looks like below. When a user clicks on alphabets from left, the right side should scroll to that alphabet heading.

Div

<div class="left">
    <ul class="letters">
        <li>
            <a href="#letter-A">A</a>
        </li>
        <li>
            <a href="#letter-B">B</a>
        </li>
    </ul>
</div>
<div class="right brands-scroll" style="max-height: 320px;overflow-y: scroll;">
    <ul>
        <li><h3 id="letter-A">A</h3></li>
        <li>Apple</li>
        <li>Alphanso</li>
        <li><h3 id="letter-B">B</h3></li>
        <li>Ball</li>
        <li>Banana</li>
    </ul>
</div>

Jquery code

$('ul.letters li a').on('click', function (t) {
    t.preventDefault();
    var targetSec = $(this).attr('href');
    $('.brands-scroll').stop().animate({
        scrollTop: $('#' + targetSec).offset().top
    }, 500);
});

I tried this solution, but it didn't work properly jQuery scroll to element

Community
  • 1
  • 1
Ashish
  • 608
  • 4
  • 16

1 Answers1

4

Try this:

$(".letters li a").click(function() {
  var container = $('.right'),id = $(this).attr('href'),
    scrollTo = $(id);

  container.animate({
    scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
  });
});

Click on any of the alphabet in the demo and you can see the result.

Working Demo

Rino Raj
  • 6,041
  • 2
  • 22
  • 37