Sanjeev K Sanjeev K - 19 days ago 8
CSS Question

Click to scroll to content within div JQuery not working correctly

I have a tabbed section which has content in div scrolling based on link clicked position but scrolling is not working properly, here is the JSfiddle demo

and this is the code firing on click

$(document).ready(function ($){
$('.scrollable_tab > ul > li > a[href^="#"]').on('click', function(event) {
var target = $(this.getAttribute('href'));
if( target.length ) {
event.preventDefault();
$('.scrollable_content_main').stop().animate({
scrollTop: target.offset().top
}, 1000);
}
});
});


Please help!

Answer

You need to take an account of the container div as well. Try like this.

$('.scrollable_tab > ul > li > a[href^="#"]').on('click', function(event) {
        var target = $(this.getAttribute('href'));
        console.log($(".scrollable_content_main").scrollTop()+target.offset().top );
        if( target.length ) {
            event.preventDefault();
            $('.scrollable_content_main').animate({
                scrollTop: $(".scrollable_content_main").scrollTop() + target.offset().top 
            }, 1000);
        }
    });

Fiddle : https://jsfiddle.net/xcht52eh/