-
-
Save dimayakovlev/9898402d13821af33b100a5c404d1038 to your computer and use it in GitHub Desktop.
Source code of the demo "Improving User Flow Through Page Transitions" on Smashing Magazine.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
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