Why is this working:
const details = document.querySelector('details')
document.getElementById("details1").addEventListener("toggle", event => {
if (details1.open) {
changeText1("open");
} else {
changeText1("closed");
}
});
document.getElementById("details2").addEventListener("toggle", event => {
if (details2.open) {
changeText2("open");
} else {
changeText2("closed");
};
});
function changeText1(status) {
if(status == "open") {
document.getElementById("p1").innerText = "opened";
} else if (status == "closed") {
document.getElementById("p1").innerText = "closed";
}
}
function changeText2(status) {
if(status == "open") {
document.getElementById("p2").innerText = "opened";
} else if (status == "closed") {
document.getElementById("p2").innerText = "closed";
}
}
<html>
<body>
<details id="details1">
<summary>#1</summary>text
</details>
<details id="details2">
<summary>#2</summary>text
</details>
<p id="p1">not opened or closed</p>
<p id="p2">not opened or closed</p>
</body>
</html>
And is this not working:
const details = document.querySelector('details')
function changeText(detailnr, status) {
let pnr = "p" + detailnr;
if(status == "open") {
document.getElementById(pnr).innerText = "opened";
} else {
document.getElementById(pnr).innerText = "closed";
}
}
function maaklistner(detailsnr){
let detailsid = "details" + detailsnr;
document.getElementById(detailsid).addEventListener("toggle", event => {
if (detailsid.open) {
changeText(detailsnr, "open");
} else {
changeText(detailsnr, "closed");
}
});
}
for(let i = 1; i < 3; i++){
maaklistner(i);
}
<html>
<body>
<details id="details1">
<summary>#1</summary>text
</details>
<details id="details2">
<summary>#2</summary>text
</details>
<p id="p1">not opened or closed</p>
<p id="p2">not opened or closed</p>
</body>
</html>
While the code in essence is exactly a duplicate...
Seems like the eventlistener itself IS created. But, the details.opened statement IS NOT treated correctly at the seconde code, while the same methode does work at the first code.
Is there a way to get the second method working? Since I need to create more then 2000 of them...
add document.getElementById(detailsid)
in place of detailsid
const details = document.querySelector('details')
function changeText(detailnr, status) {
let pnr = "p" + detailnr;
if (status == "open") {
document.getElementById(pnr).innerText = "opened";
} else {
document.getElementById(pnr).innerText = "closed";
}
}
function maaklistner(detailsnr) {
let detailsid = "details" + detailsnr;
document.getElementById(detailsid).addEventListener("toggle", event => {
if (document.getElementById(detailsid).open) {
changeText(detailsnr, "open");
} else {
changeText(detailsnr, "closed");
}
});
}
for (let i = 1; i < 3; i++) {
maaklistner(i);
}
<details id="details1">
<summary>#1</summary>text
</details>
<details id="details2">
<summary>#2</summary>text
</details>
<p id="p1">not opened or closed</p>
<p id="p2">not opened or closed</p>