Charisse Charisse - 1 year ago 105
jQuery Question

Jump to a hidden section on the same page

I have a 3 groups of content in a page that can be navigated through tabs. There's a default visible tab when I enter the page and then I can click the tabs to hide the current content and show the other.


<a href="example" name="example" class="tab active">Example</a> // default
<a href="about" name="about" class="tab">About</a>
<a href="contact" name="contact" class="tab">...</a>


<div class="example visible" id="example">...</div> // default visible content
<div class="about" id="about">...</div>
<div class="contact" id="contact">...</div>

Now, I added a footer where there are links connecting to the 3 tabs. So, if I am in a different part of the site, I can click a link, say, About Me, that would navigate to example.html and straight to the section About Me.


<li><a href="/example">Example</a></li>
<li><a href="/example#about">Example About</a></li>
<li><a href="/example#contact">Example Contact</a></li>

The above works perfectly fine. But here's the problem, when I click on the footer links while I am on example.html, it jumps to the position of the content but it cannot be seen because the current tab is still active. Is there a way to check the url whenever it changes so I can parse it and change the active tab based on it?


$(document).ready(function() {
// find which footer link was clicked; doesn't work when navigating on the same page
var hash = window.location.href.slice(window.location.href.indexOf('#') + 1);

if(hash === "foundation") {
else if(hash === "credits") {...}

// click event for tabs
$("a").on("click", function(event) {
var currentAttrVal = $(this).attr("href");
$("." + currentAttrVal).addClass("visible").siblings().removeClass("visible");

I know the script is too repetitive, but I'll refactor everything once I sort this out!

Answer Source

the location object has its own property for the current hash


this includes the hash sign too so you need


For listening to the change of the hash you will have to use the onhashchange event

You can use one of the following techniques

window.onhashchange = funcRef;  


window.addEventListener("hashchange", funcRef, false);

This way is used in frameworks like angular when they use the #! way of defining routes for browsers that do not support the History API

You can read more about it to MDN

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download