0

I would like to scroll one element into the center of another element via Javascript. Here is an example:

http://jsfiddle.net/acpnLwtw/

<div class=container>
    <div id=e1>1</div>
    <div id=e2>2</div>
    ...
</div>

How can I scroll a given element into the center of the container? A link to #e4 will almost accomplish it, but it scrolls the element to the top.

Deep Learner
  • 43
  • 1
  • 6
  • What do you mean by 'scroll into the center'? – BenM May 05 '15 at 11:39
  • @Amit what exactly did you change in that fiddle? I don't see a difference – Abdul Ahmad May 05 '15 at 11:40
  • I updated the question, so it links to a fiddle that contains a link to #e4. That almost does what i want. But it scrolls the element to the top. I want to scroll it to the center. – Deep Learner May 05 '15 at 11:44
  • possible duplicate of [How to scroll within an overflow hidden div to a certain currently invisible element?](http://stackoverflow.com/questions/11301841/how-to-scroll-within-an-overflow-hidden-div-to-a-certain-currently-invisible-ele) – wf4 May 05 '15 at 11:46
  • wf4: the answers over there scroll the element to the top. that is not my question. its already covered in my example. Also im hoping for something simpler then a jquery solution that calculates the heights and then scrolls manually. But if I have to, I will go that route. – Deep Learner May 05 '15 at 11:48
  • http://jsfiddle.net/acpnLwtw/5/ – hywak May 05 '15 at 11:50
  • 1
    usign Jquery you can do like: http://jsfiddle.net/acpnLwtw/7/ – ketan May 05 '15 at 11:54
  • ketan: yeah, that might be it. usually i dont include jquery but this is probably way easier with jquery then without it. – Deep Learner May 05 '15 at 11:58

2 Answers2

0

Add this jQuery script

$( document ).ready(function() {
    $("#goto").click(function() {
        $(".container").scrollTop($(".container").scrollTop()+($("#e4").position().top - $(".container").height()/2) );    
    })
});

HTML modification

<div id="goto" >Go to element 4</div>

Works using jQuery. Credits ketan

Fiddle Link

Its depends upon the size of div which is to be scrolled to center. Calculation is up to you.

PrakashSharma
  • 386
  • 5
  • 16
  • This might be the right direction. In case there is no ease solution without jquery. The calculation is probably not completely right yet. For example it fails when you try it with element 6. – Deep Learner May 05 '15 at 12:10
  • Yes, It will depend on size of div that we want to scroll in center, However this is the idea. – PrakashSharma May 05 '15 at 12:12
0

You can Do it with JQuery easier then other.

$( document ).ready(function() {
    $("#goto").click(function() {
        $(".container").scrollTop($(".container").scrollTop()+($("#e4").position().top - $(".container").height()/2) );    
    })
});

Check Fiddle Here.

ketan
  • 19,129
  • 42
  • 60
  • 98