Search code examples
javascripthtmljqueryscrolltop

ScrollTo on click not scrolling to the correct list item


I have an SVG map and a list where if you click on a plot number on the map it highlights on the list.

As there are quite a few items, when you click on a plot number on the map its supposed to scroll the list on the right to the correct item.

However as you start clicking around on all different numbers you can see the scroll breaks and it no longer scrolls to the correct number.

Codepen here.

JS Code below:

$('.plot__list__item').click(function () {
    $(this).toggleClass('selected');
    $(this).siblings('li').removeClass('selected');
    $('#' + $(this).data('map')).toggleClass('selected');
    $('#' + $(this).data('map')).siblings('g').removeClass('selected');
});

$('.plot__map__item').click(function () {
    $(this).toggleClass('selected');
    $(this).siblings('g').removeClass('selected');
    $('#' + $(this).data('list')).toggleClass('selected');
    $('#' + $(this).data('list')).siblings('li').removeClass('selected');
});

$('.plot__map__item').click(function () {
    let id = $(this).data('list');
    let scrollPos = $('#' + id).position().top;
    $('.plot__list').animate({
        scrollTop: scrollPos
    }, 400);
});

Solution

  • The scroll position of the list will keep changing when you scroll it. Which is why you're getting irregular scrollpos. For example, when you initially click the 1 plot, the scrollpos will be 0. But when you scroll the list a bit it changes to a negative number and it will keep changing when you're scrolling the list.

    To fix this, Calculate the top of your list and add the list's position to it. Change your click's animate function to:

    scrollTop: $('.plot__list').scrollTop() + $('#' + id).position().top
    

    Check codepen here.