Usman Zafar
Usman Zafar

Reputation: 99

JavaScript Accoridon - Auto scroll to top of open accordion

I am trying to set up my accordion so that when a user clicks on one of the headings, the page will automatically scroll down to the top of the heading and show the open panel for that accordion item.

However, the problem I have currently is that with the code I have implemented, my screen is scrolling up, so that the heading of the accordion item, sits right at the bottom of my screen, therefore the content in the panel is off screen.

Here is my HTML code:

<div class="accordion" style="margin-bottom:30px"><b>Heading 1</b></div>
<div class="panel">
  <p class="text-light">Text 1</p>
</div>
<div class="accordion" style="margin-bottom:30px"><b>Heading 2</b></div>
<div class="panel">
  <p class="text-light">Text 2</p>
</div>  

Here is my JavaScript code:

var acc = document.getElementsByClassName("accordion");
var panel = document.getElementsByClassName('panel');

for (var i = 0; i < acc.length; i++) {
 acc[i].onclick = function() {
    var setClasses = !this.classList.contains('active');
    setClass(acc, 'active', 'remove');
    setClass(panel, 'show', 'remove');

    if (setClasses) {
        this.classList.toggle("active");
        this.nextElementSibling.classList.toggle("show");
    }

    document.body.scrollTop = this.offsetTop;
 }
}

function setClass(els, className, fnName) {
  for (var i = 0; i < els.length; i++) {
    els[i].classList[fnName](className);
  }
}

Upvotes: 0

Views: 1867

Answers (1)

Marcin O
Marcin O

Reputation: 214

this.offsetTop shows relative position to parent's element top. You should get the position relative to the top of your window. This code should work for you:

document.documentElement.scrollTop +=this.getBoundingClientRect().top

Upvotes: 0

Related Questions