HTML and CSS Reference
In-Depth Information
</head>
<body>
<p>Here's a short description.</p>
<a id="toggle" href="#">toggle</a>
<p id="long_desc">Here's a longer description, which can be shown or hidden.</p>
</body>
</html>
If you run this demo and click successively on the “toggle” link, you'll see that the
longer text description paragraph is indeed toggled on and off. You'll also notice that
when the paragraph is visible, the URL has “?show” in it, and when it's hidden, this
parameter is removed. Finally, you will notice the forward/backward navigation cycles
through these states, showing and hiding the paragraph as appropriate.
Try copying the URL while the “?show” is visible and pasting it into a new browser
tab, and you'll see that indeed the paragraph is visible—the state really was preserved
in the URL, as we wanted.
The above example keeps track of the state changes in the forward/backward queue of
the browser. For some applications, this is desirable. For other applications, polluting
the forward/backward queue with lots and lots of intermittent state changes is not
appropriate.
In this case, instead of using pushState(...) you can use replaceState(...) , which (as
the name implies) replaces the current state entry in the forward/backward navigation
with the new desired state. If we do that for our example above, it looks like this:
// ...
function showText(updateHistory) {
document.getElementById("long_desc").style.display = "block";
if (updateHistory) history. replaceState (null, null, "?show");
}
function hideText(updateHistory) {
document.getElementById("long_desc").style.display = "none";
if (updateHistory) history. replaceState (null, null, location.href.replace(/\?show/, ""));
}
// ...
Running that updated demo, you'll see that the toggling and the URL behave the same.
The only difference is that there's no forward/backward queue state to cycle through.
Discussion
Browsers have long supported a History API. The difference that HTML5 brings is the
enhanced functionality of pushState(...) , replaceState(...) , and popstate .
Before the HTML5 History API enhancements were added to browsers, the only way
to emulate the functionality described above was using the URL's “hash” (the end of
a URL that looks like “#some|stuff|here”).
 
Search WWH ::




Custom Search