Single Page Hide/show Section Based On Current Position
Solution 1:
You can achieve this simply by registering hashchange callback where hash part of the current window.location is read. You can choose different DOM selection technique than id.
<script>
$( document ).ready(function() {
$("section").hide();
$(window).on("hashchange", function(){
var hash = window.location.hash.substring(1); // hash part of url withou the first letter (#)
$("section").hide();
$("#"+hash).show();
});
});
</script>
Note that ids which are used for hidding and unhiding elements are also added.
<section id="about">
Solution 2:
Using data-index instead of #id.
Add the data-index on all li
<ulclass="nav navbar-nav"><lidata-index="about"><ahref="#about">About</a></li><lidata-index="services"><ahref="#services">Services</a></li><lidata-index="contact"><ahref="#contact">Contact</a></li></ul>
and then do the same for the sections
<sectionclass="content"data-index="services">
....
</section>
See this working fiddle for more details
Solution 3:
You should give each section an id, ie. <section id="about">
.
Change your css for section
to include a display: none
attribute
Use the following JS code:
$(document).ready(function() {
$('section').eq(0).show();
$('navbar-nav').on('click', 'a', function() {
$($(this).attr('href')).show().siblings('section:visible').hide();
});
});
Or if you follow strict ordering (ie. about is first, services second, etc.):
$(document).ready(function() {
$('section').eq(0).show();
$('.navbar-nav').on('click', 'li', function() {
$('section').eq($(this).index()).show().siblings('section:visible').hide();
});
});
Either method allows for dynamic content, although personally I'd use the last method.
Solution 4:
Add an id to the links
<li><aid="about"href="#about">About</a></li>
Add an id to the section
<section id="about-content">
Add some jquery
$("#about").click(function(){
$("#about-content").show()
$("#services-content").hide()
$("#contact-content").hide()
})
Post a Comment for "Single Page Hide/show Section Based On Current Position"