I’ve built a page that has a side navigation, where each option clicked causes a certain DIV to show and the others to be hidden. I’ve written the jQuery for this and it works like a charm.
What I’m stumped with is whether or not it’s possible have links on other pages actually link to different sections on this page. In other words, a link for “Section One” that opens this page with Section One showing, and a link for “Section Two” that opens this page with Section Two already showing.
Can anyone help?
<style type="text/css">
#content div.section { display:none; }
#content div.one { display:block; }
</style>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.7/jquery.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$('#side_nav ul li a').click(function() {
$('#side_nav ul li.current').removeClass('current');
$(this).parent().addClass('current');
var filterVal = $(this).attr('class');
$('#content div.section').each(function() {
if($(this).hasClass(filterVal)) {
$(this).fadeIn(200);
} else {
$(this).hide();
}
});
return false;
});
});
</script>
<section class="main wrapper">
<div id=side_nav>
<ul>
<li class=current><a href="#" class=one>TOPIC ONE</a></li>
<li><a href="#" class=two>TOPIC TWO</a></li>
<li><a href="#" class=three>TOPIC THREE</a></li>
</ul>
</div>
<div id=content>
<div class="section one">
<h3>Subtitle</h3>
<p>One Content</p>
<br>
<h3>Subtitle</h3>
<p>One Content</p>
</div>
<div class="section two">
<h3>Subtitle</h3>
<p>Two Content</p>
<br>
<h3>Subtitle</h3>
<p>Two Content</p>
</div>
<div class="section three">
<h3>Subtitle</h3>
<p>Three Content</p>
<br>
<h3>Subtitle</h3>
<p>Three Content</p>
</div>
</section>
Could anyone detail how I would use ‘window.location.hash’ to capture the hash tag from the incoming link click, and pass it through the Javascript above in order to display the appropriate div?
If you have the links from other pages include some extra information then when your page loads you will be able to detect which section you should be displaying.
You could provide the link class value as a hash value on the incoming links such as
yourpage.html#onethen usewindow.location.hashto retrieve the value.In your case you could then add some code to your
document.ready()handler to see if the incoming link has a value and display the section as appropriate.EDIT:
Update to include example of implementation.
Just a couple more notes, obviously this is just one way you could do it. I think these selectors should work and you also might want to sanitize the input from the hash value.