Skip to content

Instantly share code, notes, and snippets.

@abheist
Forked from luruke/smashingmagazine.js
Created January 12, 2017 13:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save abheist/3571fd0da3be986a36f5fce2d24e119d to your computer and use it in GitHub Desktop.
Save abheist/3571fd0da3be986a36f5fce2d24e119d to your computer and use it in GitHub Desktop.
Source code of the demo "Improving User Flow Through Page Transitions" on Smashing Magazine.
/*
https://www.smashingmagazine.com/2016/07/improving-user-flow-through-page-transitions/
You can copy paste this code in your console on smashingmagazine.com
in order to have cross-fade transition when change page.
*/
var cache = {};
function loadPage(url) {
if (cache[url]) {
return new Promise(function(resolve) {
resolve(cache[url]);
});
}
return fetch(url, {
method: 'GET'
}).then(function(response) {
cache[url] = response.text();
return cache[url];
});
}
var main = document.querySelector('main');
function changePage() {
var url = window.location.href;
loadPage(url).then(function(responseText) {
var wrapper = document.createElement('div');
wrapper.innerHTML = responseText;
var oldContent = document.querySelector('.cc');
var newContent = wrapper.querySelector('.cc');
main.appendChild(newContent);
animate(oldContent, newContent);
});
}
function animate(oldContent, newContent) {
oldContent.style.position = 'absolute';
var fadeOut = oldContent.animate({
opacity: [1, 0]
}, 1000);
var fadeIn = newContent.animate({
opacity: [0, 1]
}, 1000);
fadeIn.onfinish = function() {
oldContent.parentNode.removeChild(oldContent);
};
}
window.addEventListener('popstate', changePage);
document.addEventListener('click', function(e) {
var el = e.target;
while (el && !el.href) {
el = el.parentNode;
}
if (el) {
e.preventDefault();
history.pushState(null, null, el.href);
changePage();
return;
}
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment