Home > Enterprise >  How to make independents buttons
How to make independents buttons

Time:01-28

the porpuse is that when you click one button it toggle his popup and also hide the other popups if they are shown. if possible i would rather a solution in Vanilla JS here is my code:

const buttons = document.querySelectorAll("button");
const popup = document.querySelectorAll(".borderBottom");


popup.forEach(function(value, index, array) {
    for(let i = 0; i < buttons.length; i  ) {
        buttons[i].addEventListener('click', e => {
            array[i].classList.toggle("show");
        })
    }
});

CodePudding user response:

There are many, many ways of achieving this. Your beginning is a good start, but it has two main issues;

You are looping through the popups with popup.forEach() and in each iteration, you also loop through the buttons; you have nested loops. This means if you have 3 buttons, each "click" event handler is added 3 times. Just one loop is enough :)

Your .toggle() targets only the popup whose button was clicked. If you click Button1 and then Button2 the popups of Button1 were never closed.

I made one example based on your code that could still be greatly improved but hopefully points to the right direction.

const buttons = document.querySelectorAll("button");
const popup = document.querySelectorAll(".borderBottom");

// Go through all popups
popup.forEach(function(value, index, array) {

    // "index" is which popup are we looking at?
    // "buttons[index]" is the button for this popup
    buttons[index].addEventListener('click', e => {

        // If this one is open, close it and return
        if (array[index].classList.contains("show")) {
            array[index].classList.remove("show")
            return
        }

        // If not, hide the old popup if there is one
        const oldPopup = document.querySelector(".show")
        if (oldPopup) {
            oldPopup.classList.remove("show")
        }

        // Finally show the one whose button was clicked
        array[index].classList.add("show")
    })
})
    .borderBottom {
      display: none;
      z-index: 2;
      background: lightpink;
      position: absolute;
      top:2em;
      left:0.2em;
      height: 2em;
      width: 10em;
    }
    .borderBottom.show {
      display: grid;
      place-items: center;
    }
<button>B1</button>
<div ><b>Popup B1</b></div>

<button>B2</button>
<div ><b>Popup B2</b></div>

<button>B3</button>
<div ><b>Popup B3</b></div>

  • Related