Jordash
Jordash

Reputation: 3103

In Javascript or jQuery how to scroll so that an element inside another div is centered vertically and horizontally

I'm trying to use jQuery or Javascript to auto scroll so that the .innerElement is centered vertically and horizontally in the .wrapper scroll boxes.

Note that the scrollable area has to be inside of a div, it can't use the window viewport (since the final version of this will have multiple scrollable areas).

I tried this:

$('.wrapper')
  .scrollTop($('.innerElement').position().top - ($('.wrapper').height() / 2))
  .scrollLeft($('.innerElement').position().left - ($('.wrapper').width() / 2));
body {
  overflow: hidden;
}

.wrapper {
  width: 100vw;
  height: 100vh;
  overflow: auto;
}

.inner {
  width: 5000px;
  height: 5000px;
  position: relative;
}

.innerElement {
  width: 20px;
  height: 20px;
  background: #000;
  top: 1400px;
  left: 1300px;
  position: absolute;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="wrapper">
  <div class="inner">
    <div class="innerElement"></div>
  </div>
</div>

I can't wrap my head around the math on this.

Upvotes: 0

Views: 42

Answers (1)

David R.
David R.

Reputation: 361

I would recommend a different formula to calculate the required coords:

For Top offset: (ElementTop - (WrapperHeight / 2) + (ElementHeight / 2))
For Left offset: (ElementLeft - (WrapperWidth / 2) - (ElementWidth / 2))

Also you can make use of the native 'Scroll' method to achieve a smooth transition.

I attach a CodePen with the concept: https://codepen.io/geekzolanos-dev/pen/xxGEmRq

Upvotes: 2

Related Questions