2

I'd like to toggle content depending on which button I click. I have a list with events, all with a button: "show carpoolers". Every time I click the button, the list of carpoolers of that particular event should show.

  • X are all the lists of carpoolers (ul tag)
  • Y are all the buttons (h4 tag)
var x = document.getElementsByClassName("lijstcarpoolers");
var y = document.getElementsByClassName("bekijkcarpoolers");
var i;
for (i = 0; i < y.length; i++) {
  y[i].addEventListener('click', setcssclass() {
    if (x[i].style.display === "none") {
      x[i].style.display = "block";
    } else {
      x[i].style.display = "none";
    }
  });
}

How can I achieve this?

Edit:

This is a picture of all the lists:

Screenshot

'Bekijkcarpoolers', or var y are the buttons 'Bekijk medecarpoolers'. 'Lijstcapoolers', or var x are the bordered lists.

In this picture I'm showing them all. But when I put them on display: none, only the second one & fourth one open when clicking on 'Bekijk medecarpoolers'.

Edit 2

<?php
$my_attendees = tribe_tickets_get_attendees( $product_id );
?>
<h4 class="bekijkcarpoolers" style="display: block; cursor: pointer;">Bekijk medecarpoolers</h4>
<ul class="attendee_list_my_account lijstcarpoolers">
<?php
foreach ($my_attendees as $attendee) {
$user_info = get_userdata($attendee['user_id']);
?>

The H4 is the one to click on.

wimkreatix
  • 43
  • 7

1 Answers1

0

Use event delegation like so:

document.addEventListener("click", function(ev) {
  var target = ev.target;

  if(target.classList.contains("bekijkcarpoolers")) {
    var ulElement = target.nextElementSibling;
    ulElement.classList.toggle("hidden");
  }
});

This adds a click event listener to the document. When a click happens in the document, we get the target of that click and check if it is a bekijkcarpoolers element or not, if so, we get the next element sibling of this target which is our ul element and we toggle its hidden class which should show/hide it accordingly.

Then add a style:

.hidden { display: none; }

And use it to hide/show the element instead of the inline style style="display: none/block".

ibrahim mahrir
  • 31,174
  • 5
  • 48
  • 73