I have a popup login box on my site, I use <a class="logincontent">Login</a>
which then calls up this function:
document.querySelector('a.logincontent').onclick = () => {
basicLightbox.create(`
<section>
MY POPUP HTML CODE SITS IN HERE
</section>
`).show()
}
This works fine but I have the login button on multiple places on my site on the same page and I want it to call the same popup. From research I need a loop allow the multiple classes call the same function but all my attempts to get this to work have failed. If anyone can help me understand how I can achieve this that would be great?
I tried using the suggestions on this site https://dev.to/baransel/how-to-add-an-event-listener-to-multiple-elements-in-javascript-aco but I was unable to use this logic with my code.
Thanks
Eddie
You can achieve this either by using multiple selectors as shown below:
document.querySelectorAll('a.logincontent').forEach(button => {
button.onclick = () => {
basicLightbox.create(`
<section>
MY POPUP HTML CODE SITS IN HERE
</section>
`).show()
}
});
Or you could store the popup html in a variable to make it more maintainable:
const loginPopupContent = `
<section>
MY POPUP HTML CODE SITS IN HERE
</section>
`;
document.querySelectorAll('a.logincontent').forEach(button => {
button.onclick = () => basicLightbox.create(loginPopupContent).show()
});
Changes I made to the code are:
querySelectorAll()
instead of querySelector()
to select all matching elementsforEach()
to attach the click handler to each buttonMake sure all your buttons have the logincontent
class:
<a href="#" class="logincontent">Login</a>
<a href="#" class="logincontent">Login Here</a>
<!-- etc -->