Search code examples
jquerysmooth-scrolling

Smooth Scrolling Child Element of Document without Scrolling Document


There's a million answers to the typical smooth scroll. What's different is that I'm trying to get element2 (with scroll bar) to smooth scroll when clicking on a link in element1. Maybe this isn't possible. The element scrolls (not slow), and unfortunately the parent window scrolls also. I'll get to the HTML, jQuery, & CSS...

HTML:

<div class="element1">
<a href="#123">Click to See Listing</a>
<a href="#124">Click to See Listing</a>
<a href="#125">Click to See Listing</a>
</div>

<div class="element2 listings">
<div class="listing" id="123">element contents</div>
<div class="listing" id="124">element contents</div>
<div class="listing" id="125">element contents</div>
etc. etc.
</div>

jQuery:

<script>
    jQ=jQuery.noConflict();
    jQ(document).ready(function(){
        jQ("a").on('click', function(event) {
            if (this.hash !== "") {
                event.preventDefault();
                var hash = this.hash;
                jQ('html, body').animate({
                    scrollTop: jQ(hash).offset().top-100
                }, 800);
            }
        });
    });
</script>

I've also tried jQ('.listings') instead of jQ('html, body')

CSS:

.listings {
width:300px;
height:500px;
overflow-y:scroll;
}

Solution

  • You can use

    $('.listings').animate({
          scrollTop: ($(hash).offset().top + $('.listings').scrollTop())- 20
     }, 800);
    

    The problem is when you are including the offset() you also need to include the current scrollvalue of the scrollContainer

    Attached a fiddle for ref https://jsfiddle.net/70b9mry4/