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

9
  • Have you seen this harvesthq.github.io/chosen ? Commented Apr 11, 2016 at 9:11
  • It would be great if you provide jquery code that you tried. Commented Apr 11, 2016 at 9:11
  • @Developer107 Jquery code added Commented Apr 11, 2016 at 9:14
  • $(this).attr('href') will give you '#letter-A' for instance which is then added with selector again as $('#'+'#letter-A') Please remove the extra # Commented Apr 11, 2016 at 9:18
  • 1
    @Developer107 the fiddle you provided is wrong. Click on A twice. It will break. Commented Apr 11, 2016 at 9:34

1 Answer 1

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

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.