I’m using Javascript to create some page transition effect to avoid reloading pages while navigating on 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 new content of the page.
The issue is, when I have a link inside the main content main, the link doesn’t trigger the page transition. It only works with the links inside the menu.
Well remember that if you change part the DOM you are going to have to rebind your event listeners in that part of the DOM. So right now you are adding a click event to all links when you first load the page, but then when you click the link in the body, you are changing that part of the page, but never rebinding the click event to those new links.
So what you want to do that after the page has transitioned, look to bind a new event listener for click events to the body again. (Be mindful however that you don’t add several events over and over again or you can cause issues).
Thanks @James_Hibbard, you’re right! It works with the uppercase A. I was wondering, would it possible to target the node a but with also this selector parameter a:not([data-no-transition])?
Thank you @Martyr2 for showing me the right direction. The solution is to add the uppercase inside the event delegation as mentioned by @James_Hibbard.
I know you have moved on to event delegation, but just for future reference a nodelist has the forEach method on it’s prototype, so there is no need to convert it to an array first.
Thank you @James_Hibard, this is exactly the method I was looking for. I didn’t know about .closest. For example in my webdev project, I have images img include inside the tag a, so the click event didn’t work.
However, I’m not sure to understand where would you use the code you provided inside the click event:
const link = e.target.closest('a:not([data-no-transition])');