KJSR
KJSR

Reputation: 1757

JQuery ScrollTop doesn't scroll to the right item

I am trying to scroll to an item inside a div container. The scroll to top function works however it seems to overshoot the item.

Javascript

<script>
$(document).ready(function () {
    var container = $('#directory'),
        scrollTo = $('.highlight_bg');
    container.animate({
        scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
    }, 2000);
});
</script>

HTML:

<div id="directory" class="directory" style="height: calc(100% - 111px)">
   <div class="directoryitem"></div>
   <div class="directoryitem"></div>
   <div class="directoryitem highlight_bg"></div>
   <div class="directoryitem"></div>
</div>

So the end is to scroll to the div item with class name highlight_bg

Not sure where am going wrong?

Upvotes: 0

Views: 495

Answers (1)

Robiseb
Robiseb

Reputation: 1606

Your Javascript code is actually working. So maybe a CSS issue ?

$(document).ready(function () {
    var container = $('#directory'),
        scrollTo = $('.highlight_bg');
    container.animate({
        scrollTop: scrollTo.offset().top - container.offset().top + container.scrollTop()
    }, 2000);
});
/* DEMO STYLISING PART */

.directoryitem {
  display: block;
  height: 90%;
  width: 90%;
  background-color: #CCC;
  border: 5px solid gray;
}
.highlight_bg {
  background-color: green;
}

/* SCROLL PART */

html, body {
  height: 100%;
  width: 100%;
}

.directory {
  position: relative;
  height: 100%;
  width: 100%;
  overflow: auto;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="directory" class="directory" style="height: calc(100% - 111px)">
   <div class="directoryitem"></div>
   <div class="directoryitem"></div>
   <div class="directoryitem highlight_bg"></div>
   <div class="directoryitem"></div>
</div>

Upvotes: 1

Related Questions