开发者

jQuery Toggle & Anchor Links

开发者 https://www.devze.com 2023-04-03 03:46 出处:网络
I\'m using a jQuery toggle effect from Sohtanaka in order to \'show\' and \'hide\' content. This is the jQuery:

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 correspo开发者_开发百科nding 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.


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();
});


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


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

0

精彩评论

暂无评论...
验证码 换一张
取 消