I\'m working on a single page websites with each page organized into section tags. Every section is placed on top of each other. I need a way with jquery, where based on cur
Add an id to the links
<li><a id="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()
})
WORKING EXAMPLE HERE
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.
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">
Using data-index instead of #id.
Add the data-index on all li
<ul class="nav navbar-nav">
<li data-index="about"><a href="#about">About</a></li>
<li data-index="services"><a href="#services">Services</a></li>
<li data-index="contact"><a href="#contact">Contact</a></li>
</ul>
and then do the same for the sections
<section class="content" data-index="services">
....
</section>
See this working fiddle for more details