When you are using ViewTransitions you can just wrap your code into this code.
document.addEventListener("astro:page-load", () => { // Your code here });
You can find more information in this video. And also in documentation.