Timberman
Timberman

Reputation: 705

Is it possible to scroll within an element with Jquery?

I'm trying to scroll down in a specific element on a page. I have already tried scrolling down like so

$('html,body').animate({
        scrollTop: $(window).scrollTop() + 100
    })

Allthough i don't want to scroll the page down, i want to scroll inside an element. The solution doens't have to be in jquery, but it is prefered

EDIT: Also tried the following

$('._1mseJ').eq(0).animate({
        scrollTop: $(window).scrollTop() + 100
    })

Upvotes: 0

Views: 62

Answers (1)

nonopolarity
nonopolarity

Reputation: 150996

This is to scroll to the end:

$container[0].scrollTop can be of the range 0 to $container[0].scrollHeight - $container[0].clientHeight, which means scrolled to the very end:

let $container = $("#container");

$container.animate({
  scrollTop: $container[0].scrollHeight - $container[0].clientHeight
}, 2000);

$container.on("scroll", function(ev) {
  $container.css({
    background: ($container[0].scrollTop === $container[0].scrollHeight - $container[0].clientHeight) ? "yellow" : "#ffc"
  });
});
#container {
  font-size: 128px;
  width: 128px;
  height: 160px;
  overflow: scroll;
  border: 1px dotted #07f;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
scrolling by user to the end => yellow background.<br> jQuery scrolling to the end also follows that rule.
<div id="container">
  1 2 3 4 5 6
</div>

Upvotes: 2

Related Questions