3

[JavaScript] HTML Web History API Example

 2 years ago
source link: http://siongui.github.io/2017/01/04/javascript-html-web-history-api-example/
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

[JavaScript] HTML Web History API Example

January 04, 2017

Change browser URL without reloading the whole web page - only partially update the content of the web page, improve the user experience of visiting your website. This is done via HTML history API.

I simplify the example in the tutorial of CSS-Tricks [3]. In the example below, I create three links, and if users click the link, the browser URL will change, and update the texts correspondingly without reloading. When users move backward or forward through the history, web page will also be partially updated.

Demo

index.html | repository | view raw

<!doctype html>
<html>
<head>
  <meta charset="utf-8">
  <title>JavaScript HTML History API Demo</title>
</head>
<body>

<div><a class="person" href="/p1/" data-content="content of person 1">person 1</a></div>
<div><a class="person" href="/p2/" data-content="content of person 2">person 2</a></div>
<div><a class="person" href="/p3/" data-content="content of person 3">person 3</a></div>
<hr>
<div id="info">Entry Page</div>

<script src="app.js"></script>
</body>
</html>

app.js | repository | view raw

"use strict";

var info = document.getElementById("info");
var persons = document.querySelectorAll(".person");

var i;
for (i=0; i<persons.length; i++) {
  persons[i].addEventListener("click", function(event) {
    event.preventDefault();
    var person = event.target;
    var href = person.getAttribute("href");
    var content = person.dataset.content;
    window.history.pushState(content, null, href);
    info.innerHTML = content;
  }, false);
}

window.addEventListener("popstate",function(event) {
  if (event.state === null) {
    info.innerHTML = "Entry Page";
  } else {
    info.innerHTML = event.state;
  }
}, false);

For GopherJS version, see [4].


Tested on:

  • Ubuntu Linux 16.10
  • Chromium Version 55.0.2883.87 Built on Ubuntu , running on Ubuntu 16.10 (64-bit)

References:

[2]Manipulating the browser history - Web APIs | MDN


About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK