How to scroll to the top of the selected accordion panel when it opens?

For example, I open a panel which has content larger than the viewable area, so I have to scroll down to view it all. At the bottom of the panel I click on the next panel header. The first panel collapses and the second one opens, but since I was already scrolled down I’m now still scrolled down and not at the top of the newly opened panel.

I figured I could use ScrollTo() on an open event of some sort but since your accordion object is automatic I don’t have an event to tie into. So how would I accomplish this?

Hi @Vincent_Wansink :wave:

In this case you need to add the scrollTo() function to the onItemTap event, like this:

onItemTap: function (event, inst) {
   window.scrollTo(0, 0);

Thanks Elod, but where would I put this? I don’t have any initialization code for the accordion. It just happens by magic.

So far I’ve got this but it only works in certain scenarios.

  var panel = document.getElementById($(this).attr("id"));

If I click on a panel that’s above the current panel, it works perfectly, but if I click on a panel that’s below the current panel it’s off. I think what it’s doing is, it’s calculating the “scroll to point” before the previously expanded panel is collapsed, so then when the previous panel collapses, everything moves up and it’s no longer scrolled to the right position.

I also tried calling the scrollIntoView with a setTimeout but that didn’t make any difference, which is weird because if I stop at that point in the debugger and then let it run, then it works perfectly every time. So stopping in the debugger makes it work, but pausing with a setTimeout does not work.

Anyway, maybe if I can call this function on a different event that would solve my problem but I don’t know what event that would be.

So it turns out I had to take an entirely different approach because my accordion is inside a scrollable div. So I had to calculate the scroll position within that div and then use scrollTop on that div. What I ended up with was this:

  var padding = 20;
  var panelindex = $(this).parent().index();
  var offset = padding + panelindex * 50;

  document.getElementById('formspace').scrollTop = offset;

This works.