Short

web stuff

View transition API with multiple images

By using window.addEventListener('pageswap') and window.addEventListener('pagereveal') you can add and remove viewTransitionName on an element at the last moment, so you don't have to hardcode viewTransitionName on each single image in your page.

I'm not here to teach you all about view transition API, but to give a way to achieve something; For instance you have a dynamic shop, and you want to transition the image on the main page to the detail page, as you may know you can't give the same viewTransitionName to two elements in the same page, so what if you have 100 products?

Fortunately you can use a technic in which you add the necessary viewTransitionName to the image that that user clicked on, and then remove if after transition finished, so this way never two elements have the same name at the same time.

let eventTarget;
if (document.startViewTransition) {
    document.addEventListener('click', (event) => {
        if (event.target.tagName.toLowerCase() === 'a') {
            eventTarget = event.target;
        }
    });

    window.addEventListener('pageswap', (event) => {
        eventTarget.style.viewTransitionName = 'image-zoom';
        
    });

    window.addEventListener('pagereveal', async (event) => {
        await event.viewTransition.finished;
        eventTarget.style.viewTransitionName = 'none';
    });
}

Note that all pages have to have this enabled in css ->

@view-transition {
    navigation: auto;
}

So what I'm doing here is that first I wanna know what element user has clicked, if it's a tag, meaning it's an image that goes into its detail page in which there's the same exact image, so I wanna transition it. Then it's simple, add the viewTransition and remove it after the transition finished.

Note that you should give the same viewTransition to the corresponding image on the other page as well for this to work, you can hard code that probably, since it's going to be one image in each detail page.