Show/Hide Divs based on Anchor Href attr that matches the Hash in the URL
-
21-12-2019 - |
質問
I have found a lot of info on URL's with Hash, but nothing to solve this. I have divs that are hidden then shown when you click it's parent. What I want to add in is if you come in with a #Hash tag that matches the anochor's href attr - trigger it was clicked.
Code I have now:
$('.speaker_container').on('click','.speaker_img',function(){ $(this).siblings('.speaker-bios').toggle(150);});
<section id="speakers">
<div class="speaker_container clearfix">
<div class="speaker_img">
<a class="speaker_img" href="#speaker1"><img>Text</a>
</div>
<h3>Name</h3>
<p class="clearfix">Text</p>
<div class="speaker-bios" style="display: none;">
<p>Hidden text</p>
</div>
</div>
<div class="speaker_container clearfix">
<div class="speaker_img">
<a class="speaker_img" href="#speaker2"><img>Text</a>
</div>
<h3>Name</h3>
<p class="clearfix">Text</p>
<div class="speaker-bios" style="display: none;">
<p>Hidden text</p>
</div>
</div>
and so on....
`
解決
This should do the trick.
$(function(){
var hash = window.location.hash;
if(hash != 'undefined'){
$('a[href='+hash+']').parents('div.speaker_container').trigger('click');
}
});
他のヒント
How about (if JQuery)
var hash = window.location.hash;
$(hash).show();
所属していません StackOverflow