Domanda

I am trying to fine-tune the UI of an app and essentially have two lists (listA and listB)... list A has hyperlinks that should, upon click, automatically scroll listB to the specific corresponding element in listB. For now I'd settle on it just scrolling to the TOP EDGE of the element but ideally it would scroll so the item is in the center (vertical) of listB.

heres a fiddle that shows what I've attempted and it works on the first click, but any subsequent click produces erratic results:

fiddle experiment / demo

I believe my issue is related to this line of code in the fiddle example -- where Im trying to accomplish the scroll:

$('#listingB').animate({ 
scrollTop: (($('#listingB_item_' + $(this).data('num')).offset().top - $("#listingB").offset().top) )
}, 'slow');

how can I make this work so that each click results in listB scrolling to the corresponding item?

È stato utile?

Soluzione

JSFiddle: working code

your first problem, going top on second click is because you need to cancel the behavior if its the second click in a row. and you also need to add $("#listingB").scrollTop() value to the animation value cause once you are scrolled in B listing your calculation will not work as expected. laslty, if you need to show the center of the element, you should calculate the height of it and add the half of that value to scrollTop. here is how you should do it:

var i;
var clicked;
for(var i = 0; i < 200; i++) {
    $('#listingB').append('<div id="listingB_item_' + i +'" class="items" data-num="'+ i +'"></div>');
    $('#listingB_item_' + i).html('item number ' + i);

    $('#listingA').append('<div id="listingA_item_' + i +'" class="items1" data-num="'+ i +'"></div>');
    $('#listingA_item_' + i).html('item number ' + i);
}

$('.items1').click( 
    function() {
        if($(this).data('num') != clicked)
        {
            clicked = $(this).data('num');
            $('#listingB').animate({scrollTop: (($('#listingB_item_' + $(this).data('num')).offset().top - $("#listingB").offset().top) + $("#listingB").scrollTop() + ((parseInt($(".items").css("padding-top")) + parseInt($(".items").css("height"))) / 2) + 'px' )}, 'slow');
        }
    }
);

Altri suggerimenti

Use an anchor with the href set to #IdOfDivYouWantToScrollTo

<a href="#yourDivId">This link will scroll to the div</a>

<div id="yourDivId">Hello</div>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top