简体   繁体   中英

Accordion scroll to top when clicked?

I have these accordions that open and close. I'd also like the accordion to scroll to the top of the page when it's clicked.

HTML:

<button class="accordion"><h2>Title</h></button>
<div class="panel">
<p>some text</p>
</div>

Javascript that works to open and close the accordion:

var acc = document.getElementsByClassName("accordion");
var i;

for (i = 0; i < acc.length; i++) {
  acc[i].addEventListener("click", function() {
    /* Toggle between adding and removing the "active" class,
    to highlight the button that controls the panel */

    this.classList.toggle("active");

    /* Toggle between hiding and showing the active panel */
    var panel = this.nextElementSibling;
    if (panel.style.display === "block") {
      panel.style.display = "none";
    } else {
      panel.style.display = "block";
    }
  });
} 

Javascript I tried to add to make it scroll to the top but it doesn't work:

$('button').click(function() {  
  $(this).animate({    
      scrollTop:0              
  }, 1000);                    
});

So, I think you can change your approach.

Considering you're using jQuery, your HTML can be like this:

...
<div class="accordion">
  <div class="accordion-header">Your accordion header</div>
  <div class="accordion-content">Your Accordion Content</div>
</div>
...

your Javascript like this:

function scrollToElement($el, time = 500){
    $([document.documentElement, document.body]).animate({
    scrollTop: $el.offset().top
  }, time);
}

function setupAccordion(){
  $('.accordion .accordion-header').click(function(){
    let $parent = $(this).parent();
    $parent.toggleClass('active');
    scrollToElement($parent);
  });
}

$(document).ready(function(){
    setupAccordion();
});

And your CSS like this:

.accordion-header{
  border-bottom:1px solid #ccc;
  padding:1em;
  cursor:pointer;
  font-weight:bold;
}

.accordion-content{
  max-height:0;
  opacity:0;
  visibility:hidden;
  transition:all 0.2s ease;
  padding:0;
}

.accordion.active .accordion-content{
  max-height:500px;
  visibility:visible;
  opacity:1;
  padding:1em;
}

Playground : https://jsfiddle.net/m0fbq2j4/

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM