dimaa
dimaa

Reputation: 35

On click scroll inside div

I have a wrapping block (like sidebar) with smaller block inside. I want to make the smaller block scroll to the top of the wrapping block (and it would look like a title) when clicked.

I have tried a lot of stuff but nothing works, I just can't understand the logic how it must work.

$(".second").click(function() {
  $('.wrap').animate({
      scrollTop: $(".second").offset().top
    }, 'slow');
});

Update: I think I explained my problem wrong. Maybe this way: Imagine long list of contacts and when you click on certain contact, all content scrolls until this contact will be at the top of visible area.

Updated jsFiddle

Sorry for bad english.

Upvotes: 3

Views: 2697

Answers (1)

Manuel Otto
Manuel Otto

Reputation: 6540

You need to determine the elements position inside the scrollable div and add that to the current scrollTop value:

scrollTop: $(e.currentTarget).position().top + $('.wrap').scrollTop()

jsfiddle

Upvotes: 4

Related Questions