willy.club/public/static/js/jarring.js

39 lines
1.3 KiB
JavaScript
Raw Normal View History

2023-02-08 14:00:14 +00:00
/**
* Reloading the page can feel jarring!
* Replace the content of the page without reloading the DOM
*/
onclick = (e) => {
let element = e.target;
if (element.tagName == 'A') {
2023-02-12 13:54:12 +00:00
navigate(element.href).then(function(url) {
window.history.pushState('', '', url);
2023-02-08 14:00:14 +00:00
});
return false; // prevent default action and stop event propagation
}
};
onpopstate = () => {
navigate(document.location);
};
function navigate(href) {
2023-02-12 13:54:12 +00:00
document.body.className = 'leaving';
2023-02-08 14:00:14 +00:00
return new Promise((resolve) => {
fetch(href)
2023-02-12 13:54:12 +00:00
.then(async (response) => {
html = await response.text();
2023-02-08 14:00:14 +00:00
//var parser = new DOMParser();
//var doc = parser.parseFromString(html, 'text/html');
//document.getElementById('pageContent').innerHTML = doc.getElementById('pageContent').innerHTML;
2023-02-12 13:54:12 +00:00
setTimeout(() => {
document.body.parentNode.innerHTML = html;
document.body.className = 'entering';
}, 250);
resolve(response.url);
2023-02-08 14:00:14 +00:00
}).catch(function (err) {
// There was an error
console.warn('Something went wrong.', err);
});
}
);
}