website/assets/script/navigation.js

69 lines
1.9 KiB
JavaScript

// @license magnet:?xt=urn:btih:1f739d935676111cfff4b4693e3816e664797050&dn=gpl-3.0.txt GPL-3.0
window.addEventListener("load", makeLinksDynamic, false);
function makeLinksDynamic() {
var navLinks = document.getElementsByClassName("nav-button");
for (var i = 0; i < navLinks.length; i++) {
navLinks[i].onclick = function(e) {
var event = e || window.event;
var target = event.target || event.srcElement;
if (target.nodeName !== "A" || event.ctrlKey || document.body.className.indexOf("loading") !== -1) return;
loadUrl(target.href, function() {
if (window.history && history.pushState) {
history.pushState(null, "", target.href);
}
});
event.preventDefault();
event.returnValue = false;
}
}
}
window.addEventListener("popstate", function() {
loadUrl(location.href);
}, false);
function loadUrl(href, callback) {
document.body.className += " loading";
var xhr = new XMLHttpRequest();
xhr.onreadystatechange = function() {
if (this.readyState === 4) {
if (this.status !== 200) location.href = href;
try {
var tags = ["main", "nav"];
for (var i = 0; i < tags.length; i++) {
document.querySelector(tags[i]).innerHTML = this.responseText.match(new RegExp("<" + tags[i] + ">([\\s\\S]+)<\\/" + tags[i] + ">"))[1];
}
} catch(e) {
location.href = href;
}
// Dispatch load event
var loadEvent = document.createEvent('Event');
loadEvent.initEvent('load', false, false);
window.dispatchEvent(loadEvent);
if (callback) callback();
document.body.className = document.body.className.replace(/\s*loading/g, "");
}
}
xhr.open("GET", href);
xhr.send();
}
// @license-end