Home > Blockchain >  how to set max of opened details in html?
how to set max of opened details in html?

Time:11-09

what this code does is set the max of opened details to 1 what I want is to set it to 3 I haven't found an answer yet

            const details = document.querySelectorAll("details");
            details.forEach((targetDetail) => {
                targetDetail.addEventListener("click", () => {
                    details.forEach((detail) => {
                        if (detail !== targetDetail) {
                            detail.removeAttribute("open");
                        }
                    });
                });
            });
       <details>
            <summary>test0</summary>
            0
        </details>
     
        <details>
            <summary>test1</summary>
            1
        </details>
        <details>
            <summary>test2</summary>
            2
        </details>
         <details>
            <summary>test3</summary>
            3
        </details>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

An easy solution is to keep track of the nodeList indexes with an Array. I made one for you called openDetails. Then when u open a detail it gets added to the array. When u close it, it gets removed. When u have 3 items u can check the first item of the list, close the corresponding detail and then remove it from the list.

let openDetails = [];

const details = document.querySelectorAll("details");

details.forEach((targetDetail, index) => {
  targetDetail.addEventListener("click", (event) => {
    const detailIsOpen = openDetails.includes(index);

    if (detailIsOpen) {
      openDetails = openDetails.filter((item) => item !== index);
    } else {

      if (openDetails.length > 2) {
        const indexToClose = openDetails[0];
        openDetails = openDetails.filter((item, i) => i !== 0);
        details[indexToClose].removeAttribute("open");
      }

      openDetails.push(index);
    }

  });
});
<details>
  <summary>test0</summary>
  0
</details>

<details>
  <summary>test1</summary>
  1
</details>
<details>
  <summary>test2</summary>
  2
</details>
<details>
  <summary>test3</summary>
  3
</details>
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

CodePudding user response:

Instead of this,

  const details = document.querySelectorAll("details");
            details.forEach((targetDetail) => {
                targetDetail.addEventListener("click", () => {
                    details.forEach((detail) => {
                        if (detail !== targetDetail) {
                            detail.removeAttribute("open");
                        }
                    });
                });
            });

Try This One, might work for you

  • Related