michaelmcgurk
michaelmcgurk

Reputation: 6509

Target specific item in Accordion with jQuery

I'd like to link to a specific panel in my accordion from another page (e.g. page.html#secondItem). I have read I've to use location.hash but unsure how to in this example.

Can someone please advise.

Demo: http://jsbin.com/macamorasi/1/edit?html,css,js,output

$(document).ready(function($) {
    $('#accordion').find('.accordion-toggle').click(function(){

      //Expand or collapse this panel
      $(this).next().slideToggle('fast');

      //Hide the other panels
      $(".accordion-content").not($(this).next()).slideUp('fast');

    });
  });
.accordion-toggle {cursor: pointer;}
  .accordion-content {display: none;}
  .accordion-content.default {display: block;}
<div id="accordion">
  <h4 class="accordion-toggle" id="firstItem">Accordion 1</h4>
  <div class="accordion-content default">
    <p>Cras malesuada ultrices augue molestie risus.</p>
  </div>
  <h4 class="accordion-toggle" id="secondItem">Accordion 2</h4>
  <div class="accordion-content">
    <p>Lorem ipsum dolor sit amet mauris eu turpis.</p>
  </div>
  <h4 class="accordion-toggle" id="thirdItem">Accordion 3</h4>
  <div class="accordion-content">
    <p>Vivamus facilisisnibh scelerisque laoreet.</p>
  </div>
</div>

http://jsbin.com/macamorasi/1/edit?html,css,js,output

Upvotes: 0

Views: 695

Answers (1)

Terry
Terry

Reputation: 66188

You can check if location.hash exists. If it does, use it to find the element of interest and then slide it down. You can then use .siblings() to find other <h4> elements, and get their next neighbour and slide them up.

$(document).ready(function($) {
  // General accordion click toggle
  $('#accordion').find('.accordion-toggle').click(function(){

    //Expand or collapse this panel
    $(this).next().slideToggle('fast');

    //Hide the other panels
    $(".accordion-content").not($(this).next()).slideUp('fast');

  });

  // Check for location hash
  if(location.hash) {
    // Remove the first '#' character
    var hash = location.hash.substr(1);

    // Expand element 
    if($('#'+hash).length) {
      $('#'+hash)
        .next()
          .slideDown()
          .end()
        .siblings('h4')
          .next()
          .slideUp();
    }
  }
});

See the full code here: http://jsbin.com/bonozoqezo/1/edit. For a proper demo, access full screen demo with a hash: http://jsbin.com/bonozoqezo/1#secondItem

Upvotes: 1

Related Questions