Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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;
}
});
@boehs
Copy link

boehs commented Jul 29, 2021

Pretty good starting point, but the code could use some modernization, for instance

function loadPage(url) {
  if (cache[url])
    return new Promise(resolve => resolve(cache[url]));

  return fetch(url).then(res => {
    cache[url] = res.text();
    return cache[url];
  });
}

@m-naeem66622
Copy link

m-naeem66622 commented Jan 12, 2022

Your source is not working. It is just changing the URL in the browser but no content changing. It is giving me an error as follows :
"Uncaught (in promise) TypeError: Cannot read properties of null (reading 'appendChild') at 36:8"
Please help me.....

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment