I have some typical tab content and I really need some help. I would like to achieve, that when user tries to get to a specific tab via external anchor link (http://www.url.com#content2), the navigation link becomes activated and the correct tab is shown.
Thank you for your help.
HTML
<nav class="inner-nav">
<ul>
<li><a href="#content1">Inner nav navigation link1</a></li>
<li><a href="#content2">Inner nav navigation link2</a></li>
<li><a href="#content3">Inner nav navigation link3</a></li>
</ul>
</nav>
<section class="tab-content" id="content1">
<article>
content1 goes here
</article>
</section>
<section class="tab-content" id="content2">
<article>
content2 goes here
</article>
</section>
<section class="tab-content" id="content3">
<article>
content3 goes here
</article>
</section>
JAVASCRIPT
$(document).ready(function () {
$(".tab-content").hide();
$(".tab-content:first").show();
$(".inner-nav li:first").addClass("active");
$(".inner-nav a").click(function(){
$(".inner-nav li").removeClass("active");
$(this).parent().addClass("active");
var currentTab = $(this).attr("href");
$(".tab-content").hide();
$(currentTab).show();
return false;
});
});
I have a live example here So, if you click on the navigation, everything works ok, but if you want to go to a specific tab kajag.com/themes/book_your_travel/location.html#sports_and_nature the correct tab does not open.
You could solve this by simply checking the hash when the page loads, and then trigger a click on the right tab, like so:
$(function () {
$(".tab-content").hide().first().show();
$(".inner-nav li:first").addClass("active");
$(".inner-nav a").on('click', function (e) {
e.preventDefault();
$(this).closest('li').addClass("active").siblings().removeClass("active");
$($(this).attr('href')).show().siblings('.tab-content').hide();
});
var hash = $.trim( window.location.hash );
if (hash) $('.inner-nav a[href$="'+hash+'"]').trigger('click');
});
I've just finished something similar here (disclosure, my site): http://kronia.com.au/#showcase
Since you're not using the hash directly (i.e. the page shouldn't scroll to a div, it should hide/show a tab depending on the value) you need to check first for a hash (there may not be a hash in the link).
if (window.location.hash){
someFunction();
}
Then show/hide tabs based on the value of the hash. If you're performing some transition, then define a 'from' and 'to' tab, otherwise just the tab that should be shown. E.g.:
function someFunction(_to, _from){
_to.removeClass('kr-dormant').addClass('kr-next');
_from.removeClass('kr-current').addClass('kr-dormant');
_to.removeClass('kr-next').addClass('kr-current');
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With