Link to anchor and open accordion

北城余情 提交于 2021-02-07 09:01:10

问题


How do I open an accordion panel by using an external anchor link?

I've tried using an anchor link and it just loads the page, without opening the panel.

What I'm trying to achieve is that when the anchor link is clicked, the page loads, scroll to the panel and then open the accordion.

This link is the one that will anchor to the other page and should open the accordion:

 <a class="linkTo" href="/project#<?php the_sub_field('area_link'); ?>">

This is the code I am using to open the accordion on click:

 $(document).ready(function() {
   $(".accordion .accord-header").click(function() {
     // for active header definition
     $('.accord-header').removeClass('on');
     $(this).addClass('on');

     // accordion actions
     if($(this).next("div").is(":visible")){
       $(this).next("div").slideUp(600);
       $(this).removeClass('on');
     } else {
       $(".accordion .accord-content").slideUp(600);
       $(this).next("div").slideToggle(600);
     }
  });
});

This is the accordion structure:

<div class="accordion">
  <div class="accord-header" id="<?php the_sub_field('area_link'); ?>">Accordion 1</div>
    <div class="accord-content">
        <!-- Content -->
    </div>
  </div>
</div>

回答1:


You can use window.location.hash on document ready to initialize your accordion.

$(function () {
    var $accordionSecion = $(window.location.hash);
    if ($accordionSecion.length) {
       $(window).scrollTop($accordionSecion.offset().top);
       $accordionSecion.addClass('on');
    }
});

You can probably use same handler with onhashschange listener to handle click on accordion titles.

Good luck. :)




回答2:


$(document).ready(function(){
 var hash = window.location.hash;
 if (hash) {
   var element = $(hash);
   if (element.length) {
   element.trigger('click');
 }
 }
});

try above code on the page where you want to open the accordion.



来源:https://stackoverflow.com/questions/49170731/link-to-anchor-and-open-accordion

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!