SugarChiffon
SugarChiffon

Reputation: 15

Scrollbar issue with JS tabs

I'm brand new to javascript, so the problem might actually lie in how much I know or how to word searches for this, but I haven't found the same problem anywhere else:

When making a set of tabs with script, they works fine, but the scrollbar will stay the same on each tab. For example, if I go to the second tab and scroll all the way down and then click on the third tab, instead of going to the top, it will stay at the bottom because that's where it was on the second tab.

This is what I'm working with: http://jsfiddle.net/z7uxfbws/

jQuery(document).ready(function() {
  jQuery('.tabs .tab-links a').on('click', function(e)  {
    var currentAttrValue = jQuery(this).attr('href');

    // Show/Hide Tabs
    jQuery('.tabs ' + currentAttrValue).fadeIn(400).siblings().hide();

    // Change/remove current tab to active
    jQuery(this).parent('li').addClass('active').siblings().removeClass('active');

    e.preventDefault(e);
  });
});

If you could explain what the problem is, how to fix it, and why it works, that would be absolutely wonderful.

Thank you for taking the time to read!

Upvotes: 1

Views: 1196

Answers (1)

Josh Crozier
Josh Crozier

Reputation: 241178

The scrollbar is on the parent element, .tab-content.

The elements that are being manipulated (hidden/shown) are the children elements, .tab.

Therefore the scrollbar on the parent element is always there. Thus, when switching tabs, the scrollbar's position doesn't change.

In order to work around this, you could move the scrollbar to the children elements rather than the parent.

Updated Example

 .tab {
     display: none;
     overflow: auto;         /* Moved this from the parent element */
     height: 100%;
     padding: 10px;          /* This *was* on the parent element, too. */
     box-sizing: border-box; /* Include the padding in the 
                                element's width/height calculations */
 }

... alternatively, you could also just scroll .tab-content's scrollbar to the top each time a tab is changed.

Updated Example

$('.tab-content').scrollTop(0);

Upvotes: 2

Related Questions