[Table of Contents] Select all .toc-link with Javascript

Hello,
I would need to make a function that is triggered when a user clicks on one of the Table of Contents elements.

I have identified the elements that are generated via the “Table of Contents” element of Bricks, namely the <a> tag that contains the “.toc-link” class.

For this I made a script of this type:

<script>
	const tocLinks = document.querySelectorAll('.toc-link');
  
  tocLinks.forEach((tocLink, index) => {
    tocLink.addEventListener('click', () => {
      myFunction(index);
    });
  });
</script>

After several tests, I noticed that the method document.querySelectorAll('.toc-link');
does not select any elements.

Can you help me understand why? Thank you.

@fabio.signoretti ,

Well received your email.

That’s because the .toc-link is not generated by PHP but via another JavaScript in Bricks.

You should amend your code like this.

<script>
	document.addEventListener( 'DOMContentLoaded', ()=>{
    
		setTimeout( ()=> {
		
			const tocLinks = document.querySelectorAll('.toc-link');

			tocLinks.forEach((tocLink, index) => {
				tocLink.addEventListener('click', () => {
				  myFunction(index);
				});
			});
			
		}, 500 )
	})
</script>

Regards,
Jenn

1 Like

check this out if you need it.

1 Like

Tanks @sinanisler !
Can you suggest me a code suitable for Bricks that does the exact same thing, but in php?