Darren
Darren

Reputation: 43

jQuery Toggle & Anchor Links

I'm using a jQuery toggle effect from Sohtanaka in order to 'show' and 'hide' content.

This is the jQuery:

$(document).ready(function(){

//Hide (Collapse) the toggle containers on load
$(".toggle_container").hide(); 

//Switch the "Open" and "Close" state per click then slide up/down (depending on open/close state)
$("h2.trigger").click(function(){
    $(this).toggleClass("active").next().slideToggle("slow");
    return false; //Prevent the browser jump to the link anchor
});

});

and this is my HTML:

<h2 class="trigger"><a href="#test1">Test 1</a></h2>
 <div class="toggle_container">
  <div class="block">
    <h3>Content Header</h3>
    <p>content</p>
  </div>
 </div>

<h2 class="trigger"><a href="#test2">Test 2</a></h2>
 <div class="toggle_container">
  <div class="block">
    <h3>Content Header</h3>
    <p>content</p>
  </div>
 </div>

<h2 class="trigger"><a href="#test3">Test 3</a></h2>
 <div class="toggle_container">
  <div class="block">
    <h3>Content Header</h3>
    <p>content</p>
  </div>
 </div>

Everything works as expected.

I'd like to know what needs to be modified so that a specific container is shown when the corresponding anchor is on the end of the url?

e.g. If my url is "www.domain.com/content/#test2" I would like container 'Test 2' to be shown and 'Test 1' and 'Test 3' to remain hidden.

Many thanks.

Upvotes: 1

Views: 7106

Answers (3)

jensgram
jensgram

Reputation: 31508

The window.location.hash will hold the value #test2 when the URL is http://www.domain.com/content/#test2. This is what you should use in the jQuery attribute selector that you use to locate the <a> element within the ready handler:

$(document).ready(function() {
    ...

    if (window.location.hash) {
        $('h2.trigger + .toggle_container').hide(); // Hide all...
        $('h2.trigger').has("a[href='" + window.location.hash + "']").next('.toggle_container').show(); // ... but show one
    }
});

(Demo. A more elegant implementation is bound to exist.)

Update
I my first answer was incorrect in many ways :-S

Upvotes: 0

Aleksandar Trajkov
Aleksandar Trajkov

Reputation: 477

$(document).ready(function() {
    $('a').each(function() {
        if($(this).attr('href') == window.location.hash) {
            $(this).parent(".trigger").click();
        }
    });
);

Upvotes: 0

hunter
hunter

Reputation: 63512

You should be able to add this functionality to your code like this:

$(document).ready(function() {
    $(".toggle_container").hide();
    $("h2.trigger").click(function() {
        $(this).toggleClass("active").next().slideToggle("slow");
        return false; //Prevent the browser jump to the link anchor
    });

    $("a[href='" + window.location.hash + "']").parent(".trigger").click();
});

Upvotes: 2

Related Questions