Search code examples
jquerymaterialize

Materialize - Collapsible with a huge content does not scroll to top of the tab


I use the collapsible component provide by materialize framework. I get one bug and have no idea how to solve it or find a workaround. If the content of one tab is too huge, when I open the tab it does not scroll to the top of the tab itself (it goes to the middle).

You can try it here : https://jsfiddle.net/r8314ouq/. Open the first tab then open the third tab you'll see that it doesn't scroll to the beggining of the tab.

I see enter image description here But I would like to see enter image description here It's very annoying because the user has to scroll to see all the content.

I followed the documentation to create my collapsible :

<ul class="collapsible" data-collapsible="accordion">
    <li>
      <div class="collapsible-header"><i class="material-icons">filter_drama</i>First</div>
      <div class="collapsible-body"><p>Lorem ipsum dolor sit amet.</p></div>
    </li>
    <li>
      <div class="collapsible-header"><i class="material-icons">place</i>Second</div>
      <div class="collapsible-body"><p>Lorem ipsum dolor sit amet.</p></div>
    </li>
    <li>
      <div class="collapsible-header"><i class="material-icons">whatshot</i>Third</div>
      <div class="collapsible-body"><p>Lorem ipsum dolor sit amet.</p></div>
    </li>
  </ul>

I tried to catch the event and do a scroll to but it didn't work. Any ideas?


Solution

  • So in terms of use-ability, due to the way the accordion effect works there is some delay, but here is a way of making this work.

    $('.collapsible').collapsible({
      accordion : false // A setting that changes the collapsible behavior to expandable instead of the default accordion style
    });
    
    $('.collapsible .collapsible-header').on('click', function(event) {
        var target = $(this);
        setTimeout(function() {
          if( target.length ) {
            event.preventDefault();
            $('html, body').animate({
                scrollTop: target.offset().top
            }, 500);
          }
        }, 300);
    });
    

    Here is your JSFiddle modified to work

    The 500 is a half-a-second animation of scroll effect, meanwhile the 300 is around a 0.3 second delay to allow the accordion to collapse, otherwise it scrolls to the headers location at the point of the event firing (click) which is about half-way through the text (when opening a header below an already open accordion section).