0

I have some simple code that hides or shows a div (that will contain an embedded contact form) when a button is clicked.

I first set it up in J4.0.3 and it works fine, but when I tried in J3.10.2 the code 'selector' is not recognised.

Here is the code (which you can also see at [codepen.io][1]

[1]: https://codepen.io/Scrabble96/pen/NWvWwOY)

In J3 the 'selector' at the end of the second line is not highlighted in blue in the editor as it is in the first line and as the other elements - 'test', 'tests', etc are.

for (const selector of [".toggle-form"]) {
    const tests = [...document.querySelectorAll(selector)];
    for (const test of tests) {
        test.addEventListener('click', () => {
            tests.filter(f => f !== test).forEach(f => {
            f.classList.remove('form-opened');
            f.setAttribute("aria-expanded", "false");
            });
        test.classList.toggle('form-opened');
        let ariaExpanded = test.classList.contains('form-opened').toString();
        test.setAttribute("aria-expanded", ariaExpanded);
        })
    }
}

Can anyone explain this and tell me what I need to do to make it work in J3x? Thanks.

0

I'm not sure why it would be working in J4, but not J3. That said, you're unecessarily using nested for loops, rather than a single forEach iterator.

You can use the following:

// Create an array using Array.from(), so that we can filter later on
const toggles = Array.from(document.querySelectorAll('.toggle-form'));

// Iterate over the array
toggles.forEach((toggle) => {
    toggle.addEventListener('click', () => {
      toggles
        .filter((f) => f !== toggle)
        .forEach((f) => {
          f.classList.remove('form-opened');
          f.setAttribute('aria-expanded', false);
        });
      toggle.setAttribute('aria-expanded', toggle.classList.contains('form-opened'));
      toggle.classList.toggle('form-opened');
    });
});

You might find this will also work on your J3 instance

4
  • Unfortunately, it still doesn't work. In the Joomla code editor the first toggles in the first line is blue, as are all instances of toggle and f, but all the other toggles are black text. I'd upload an image if I could. This is in a two-day-old installation of Protostar with no extra extensions or plugins.
    – Gillian
    Oct 10 at 17:19
  • What editor are you using? Have you tried using CodeMirror instead?
    – Lodder
    Oct 11 at 4:32
  • I am using the default Joomla 3.10x admin editor: CodeMirror - I have not changed anything in the installation
    – Gillian
    Oct 11 at 11:51
  • So when you save the content, and view the front-end of your site, are you getting any errors in your browser console?
    – Lodder
    Oct 12 at 8:12

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.