简体   繁体   中英

Link to section within Accordion using jQuery

I have 2 pages. page1.html contains a series of links & page2.html has an Accordion.

My Question: Is it possible to link directly to a section in the Accordion? So, if I wanted to visit 'Celtic', how do I create a link that a) opens correct Accordion tab b) anchors down to celtic id.

Here's my current code for page2.html : http://jsfiddle.net/7k9s1pg7/

HTML:

<dl class="accordion">

<dt><a href="" class="container heading">Soccer</a></dt>
<dd id="soccer">
  <div id="manutd">

    <p>Man Utd</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>

  </div>  

  <div id="celtic">

    <p>Celtic</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>

  </div>
</dd>

<dt><a href="" class="container heading">Formula 1</a></dt>
<dd id="formula1">
  <div id="lewishamilton">

    <p>Lewis Hamilton</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>

  </div>  

  <div id="michaelschumacher">

    <p>Michael Schumacher</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>
    <p>&nbsp;</p>

  </div>
</dd>
</dl>

Javascript:

(function($) {
    var allPanels = $('.accordion > dd').hide();
    var allLinks = $('a.heading');
    $('.accordion > dt > a').click(function() {
        allPanels.slideUp();

        allLinks.removeClass('active');

        if ($(this).parent().next().is(":visible")) return false;
        $(this).parent().next().slideDown();

        $(this).addClass('active');

        return false;
    });

})(jQuery);

Use anchors in page1 links: page2.html#lewishamilton and add to your JS code

var hash = location.hash;
if (hash) {
    var el = $(hash);
    el.parent().slideDown();
    el.parent().prev().find('a').addClass('active');
}

http://jsfiddle.net/7k9s1pg7/2/

I faced a same problem recently. I fixed it by setting up the RewriteRule in .htaccess instead of playing with the frontend code.

I did this because my requirement was to have a user-friendly URL for a better UX. The other option is to go for # ( location.hash ).

See this question and answer .

My idea was to hit a URL that looks user-friendly. Something like:

http://www.example.com/somepage/something

Where somepage is the page with the accordian and something is the ID of the button inside a section of the accordian.

In somepage , you will need to write code to read the something from the URL on onload by using window.location.pathname and then programatically click the something button.

Note that this fixes your accordian problem and also gives a good UX by rendering a user-friendly URL.

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