Benjamin G Benjamin G - 1 month ago 6
HTML Question

Reload Page (F5) with Hash Values in Url

How can I keep the

hash
value in the
url
and keep the tab or
div
open even after refreshing the page. Here is my sample code:



$( document ).ready(function() {
jQuery(function($) {
showTab(location.hash || "userView");
$("#nav a").click(function() {
var hash = this.getAttribute("href");
if (hash.substring(0, 1) === "#") {
hash = hash.substring(1);
}
window.location.hash = hash;
showTab(hash);
return false;
});

function showTab(hash) {
$(".displayUsers").hide();
switch (hash) {
case "userView": ViewUsers(); break;
case "userLogs": UserLogs(); break;
case "addUser": AddUser(); break;
}
}

});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="panel">
<dl id="nav">
<dt>
<p>•<a href="#addUser" class="listLink"> ADD USER</a></p>
</dt>
<dt>
<p>•<a href="#userLogs" class="listLink"> USER LOGS</a></p>
</dt>
<dt>
<p>•<a href="#userView" class="listLink"> VIEW USERS</a></p>
</dt>
</dl>
</div>

<div id="addUser" class="displayUsers" hidden></div>
<div id="userLogs" class="displayUsers" hidden></div>
<div id="userView" class="displayUsers" hidden></div>





After refreshing the page, the
hash
value is being kept in the
url
but the currently active
div
are being set to default - hidden.

Answer

You better parse hash in showTab function. Main problem was, you were sending hash or userView but the hash there had # at the beginning. You parse it onClick but you don't parse it onload. So I moved parsing code into the showTab function.

showTab(location.hash || "userView");
$("#nav a").click(function() {
    var hash = this.getAttribute("href");
    showTab(hash);
    return false;
});

function showTab(hash) {

    if (hash.substring(0, 1) === "#") {
        hash = hash.substring(1);
    }
    window.location.hash = hash;
    $(".displayUsers").hide();
    switch (hash) {
        case "userView":
            ViewUsers();
            break;
        case "userLogs":
            UserLogs();
            break;
        case "addUser":
            AddUser();
            break;
    }
}

function ViewUsers() {
    $("#userView").show();
}

function UserLogs() {
    $("#userLogs").show();
}

function AddUser() {
    $("#addUser").show();
}

Working fiddle https://jsfiddle.net/ergec/z02xzatj/