How can I apply my Javascript code to all members of the repeated members?
Hello everyone,
I created a drop-down module and put it in a repeater.
I wrote a Javascript code that works fine for the first object in the repeater. When I try to add another object through the repeater the functionality doesn't work for the 2nd, 3rd, ... and other reapeated members.
how can I apply the Javascript code to work for all the members of the repeater?
This is the Javascript code:
/* When the user clicks on the button, toggle between hiding and showing the dropdown content */
var button = document.querySelector(".dropbtn");
button.addEventListener("click", myFunction); function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); }
// Close the dropdown if the user clicks outside of it window.onclick = function(event) { if (!event.target.matches('.dropbtn')) { var dropdowns = document.getElementsByClassName("dropdown-content"); var i; for (i = 0; i < dropdowns.length; i++) { var openDropdown = dropdowns[i]; if (openDropdown.classList.contains('show')) { openDropdown.classList.remove('show'); } } } }
How can I apply my Javascript code to all members of the repeated members?
Not really sure what you're doing with the HTML... I only said to move the 'myDropdown' class, not change anything else. For brevity the code I provided was just a simplified version of the change, not the entire code. The entire code should look like this:
How can I apply my Javascript code to all members of the repeated members?
First, you'll wat to change your "myDropdown" ID to a class, because there should never be multiple items on a page with the same ID.
Then you'll grab all items with that class using querySelectorAll and run a forEach with your toggle code inside so that it adds event listeners to each item.
// grab all items with "myDropdown" class using querySelectorAll
const dropdowns = document.querySelectorAll('.myDropdown')
// run a forEach on your dropdowns variable
dropdowns.forEach(dropdown => {
// run your toggle code inside the forEach
// replacing all document selectors with your forEach element 'dropdown'
var button = dropdown.querySelector(".dropbtn");
button.addEventListener("click", myFunction);
function myFunction() {
dropdown.classList.toggle("show");
}
});
If this answer solved your question, please mark it as the solution.
How can I apply my Javascript code to all members of the repeated members?
Hello Alyssa,
Thanks so much for your response. I modified the code and still didnt work. I may be need to made some changes to my HTML as well. would you please on that as well?
This is my HTML code and the modified Javascript code