Site logo

Archived topic

Multiple Toggle button on single page

7 replies · Started by Scott on May 29, 2021

Viewing posts 1–8 of 8

Hello Team!

Following the advice on this post: https://generatepress.com/forums/topic/trying-to-get-a-button-to-toggle-a-div-grid/

I have successfully created a working toggle but it only works on the first instance and I am using multiple instances of the toggle on a single page.

Is there a way to add a "next" parameter like Tom did here: https://generatepress.com/forums/topic/toggle-text/ that would allow the script to only open the next container?

THANKS!
Scott

Hi Scott,

Let's modify the vanilla JS provided a bit.

We can use nextSibling with this.

Try this one.

var toggleBtn = document.querySelector('.toggle-heading');
var toggleTgt = document.querySelector('.toggle-heading').nextSibling;

toggleBtn.addEventListener("click", function() {
  toggleTgt.classList.toggle('show-text');
});

Hi Elvin!

Thanks for the reply but it's not working as expected. The first instance of the toggle button is working perfectly but the subsequent ones are not. Any other ideas? I was trying to avoid loading jquery if I can.

Thanks so much for this above and beyond help!
Scott

Thanks for the reply but it’s not working as expected. The first instance of the toggle button is working perfectly but the subsequent ones are not. Any other ideas? I was trying to avoid loading jquery if I can.

Yeah that was the goal. The script is vanilla JS. We're actually trying to avoid jquery as well. :)

I think we need to reiterate making of listeners per btn.

Example:

var toggleBtn = document.querySelectorAll('.toggle-heading');

for(i=0; i<toggleBtn.length; i++){
  var toggleTgt = toggleBtn[i].nextSibling;
  toggleBtn[i].addEventListener("click", function() {
    toggleTgt.classList.toggle('show-text');
  });
}

Having an ID means you'll have to make a script for each one.

Try this:

var toggleBtn = document.querySelectorAll('.toggle-heading');

toggleBtn.forEach(item => {
  item.addEventListener('click', event => {
    var toggleTgt = item.nextElementSibling;
    toggleTgt.classList.toggle('show-text');
  })
});

Note: Make sure the class is on the wrapper. not the actual button.

We have a winner! Works just like I wanted. Thanks so much! This is why GP is the best theme on the planet with the best support!

Nice one. Glad you got it sorted. No problem. :D

This archived topic is closed to new replies.