Web Dev Notes

Blog about web development by Robert Dawson

Hide/show info and change URL without reloading

Problem

You have a page with information by year. And year headings are linked, like this:


Information under the latest year is shown, while information under previous years is hidden. When a user clicks a year, you want to show that year's information and add a hash value (e.g., #2013) to the URL so that returning to this page will return it to the previous open/close state.

Solution

var current_path = location.pathname;
var year_hash = (location.hash.substr(1) != "") ? location.hash.substr(1) : "";

$("h2").on("click", function()
{
location.hash = $(this).text();
});

if ( location.hash.match(/^\#\d{4}$/) )
{
$("h2:first").click();
$("h2:contains(" + year_hash + ")").click();
}