Skip to content

Instantly share code, notes, and snippets.

@kalevitan
Created October 18, 2017 20:26
Show Gist options
  • Save kalevitan/fda3c55a398b499fafd3675eb9f32db2 to your computer and use it in GitHub Desktop.
Save kalevitan/fda3c55a398b499fafd3675eb9f32db2 to your computer and use it in GitHub Desktop.
Show/Hide Content with jQuery
[...]
<style>
.content { display: none; }
.content.active { display: block; }
.nav-menu > li.active a { font-weight: bold; }
</style>
<div class="container">
<nav class="nav>
<ul class="nav-menu">
<li><a href="#item1">Item 1 link</a></li>
<li><a href="#item2">Item 2 link</a></li>
<li><a href="#item3">Item 3 link</a></li>
</ul>
</nav>
<div class="content" id="item1">
<p>Item 1 content</p>
</div>
<div class="content" id="item2">
<p>Item 2 content</p>
</div>
<div class="content" id="item3">
<p>Item 3 content</p>
</div>
</div>
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<script>
// Load content if URL has predefined hash
$(window).load(function() {
// Load tab content
loadTab(location.hash);
});
$('.nav-menu > li > a').click(function(event) {
// Prevent the click as a link
event.preventDefault();
// Update window location with hash
window.location.hash = event.target.hash;
//find actived navigation and remove 'active' css
var actived_tab = $('.nav-menu > li.active');
actived_tab.removeClass('active');
// Assign active state
$(this).parents('li').addClass('active');
// Load tab content
loadTab(event.target.hash);
})
function loadTab(hash) {
// Clear all active tabs
$('.content').removeClass('active');
// Define hash if empty
if (hash === null || hash.length === 0) {
hash = '#item1';
}
// Activate content based on hash argument
$(hash).addClass('active');
}
</script>
[...]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment