I’m using Javascript to create some page transition effect without reloading pages in a website.
The interface of the website is divided in 2 parts. The first part is the menu that is present in all pages of the site. The second part is the main content that refreshs by loading the content of the page.
The issue is, when I have a link inside the main content, the link doesn’t trigger the page transition. I think the JS links selector doesn’t update once the content has been transitioned. It only works with the main menu, not with the links inside the main content.
I don’t find the way to make the JS recognizing the links inside the updated main content once it has been transitioned.
const main = document.querySelector('.js-content');
const links = [...document.querySelectorAll('a')];
let isAnimating = false;
links.forEach(link => {
link.addEventListener('click', async e => {
e.preventDefault();
if(isAnimating) return
const url = e.target.href;
console.log(url)
startTransition(url);
const pathname = new URL(url).pathname;
history.pushState(null, '', pathname);
})
})
window.addEventListener('popstate', e => {
const url = window.location.pathname;
startTransition(url)
})
const startTransition = async (url) => {
isAnimating = true;
const html = await fetch(url);
const htmlString = await html.text();
const parser = new DOMParser();
const parsedhtml = parser.parseFromString(htmlString, 'text/html').querySelector('.js-content')
transitionDiv.classList.add('is-animate-in');
transitionDiv.addEventListener('transitionend', () => {
main.innerHTML = parsedhtml.innerHTML;
transitionDiv.classList.remove('is-animate-in');
transitionDiv.classList.add('is-animate-out');
setTimeout(() => {
transitionDiv.style.transition = '0s';
transitionDiv.classList.remove('is-animate-out');
setTimeout(() => {
transitionDiv.style.transition = '1s';
}, 100)
isAnimating = false;
}, 1000)
}, {once: true})
}
