Albeld
Albeld

Reputation: 141

How can I get this code working for all Buttons?

I try to build a landing page, where a box with a form pops up when the user clicks on contact.

I've added a modal script which works great, but only for one button. I added the id or class for all buttons but it's just not working.

<button class="trigger">Click here to trigger the modal!</button>
<div class="modal">
    <div class="modal-content">
        <span class="close-button">×</span>
        <h1>Hello, I am a modal!</h1>
    </div>
</div>
var modal = document.querySelector(".modal");
var trigger = document.querySelector(".trigger");
var closeButton = document.querySelector(".close-button");

function toggleModal() {
    modal.classList.toggle("show-modal");
}

function windowOnClick(event) {
    if (event.target === modal) {
        toggleModal();
    }
}

trigger.addEventListener("click", toggleModal);
closeButton.addEventListener("click", toggleModal);
window.addEventListener("click", windowOnClick);

I would like to be able to add the '.trigger' to any button or a-tag and have it working.

Upvotes: 1

Views: 75

Answers (1)

AbbasEbadian
AbbasEbadian

Reputation: 693

You can do it like this:

triggers=document.getElementsByClassName('trigger');
for (let i=0;i< triggers.length;i++){
    triggers[i].addEventListener("click", toggleModal);
}

This snippet adds Event listener to all '.trigger' classed tags.

Upvotes: 3

Related Questions