I’ve been struggling all day now why a certain JS function stopped working after an AJAX request is called. It must have something to do with the query selector. But I just can’t figure out what’s going on there!
( function() {
'use strict';
if ( 'querySelector' in document && 'addEventListener' in window ) {
const select = document.querySelectorAll( '.Accordion-panel select' );
const input = document.querySelectorAll( '.Accordion-panel input' );
if ( select.selected ) {
document.getElementsByClassName( 'Accordion-trigger' ).setAttribute( 'aria-expanded', 'true' );
document.getElementsByClassName( 'Accordion-panel' ).removeAttribute( 'hidden' );
} else {
document.getElementsByClassName( 'Accordion-trigger' ).setAttribute( 'aria-expanded', 'false' );
document.getElementsByClassName( 'Accordion-panel' ).setAttribute( 'hidden', '' );
}
if ( input.checked ) {
document.getElementsByClassName( 'Accordion-trigger' ).setAttribute( 'aria-expanded', 'true' );
document.getElementsByClassName( 'Accordion-panel' ).removeAttribute( 'hidden' );
} else {
document.getElementsByClassName( 'Accordion-trigger' ).setAttribute( 'aria-expanded', 'false' );
document.getElementsByClassName( 'Accordion-panel' ).setAttribute( 'hidden', '' );
}
document.addEventListener( 'click', function( event ) {
const target = event.target;
if ( target.classList.contains( 'Accordion-trigger' ) ) {
// Check if the current toggle is expanded.
const isExpanded = target.getAttribute( 'aria-expanded' ) == 'true';
if ( ! isExpanded ) {
// Set the expanded state on the triggering element.
target.setAttribute( 'aria-expanded', 'true' );
// Hide the accordion sections, using aria-controls to specify the desired section.
document.getElementById( target.getAttribute( 'aria-controls' ) ).removeAttribute( 'hidden' );
} else {
// Set the expanded state on the triggering element.
target.setAttribute( 'aria-expanded', 'false' );
// Hide the accordion sections, using aria-controls to specify the desired section.
document.getElementById( target.getAttribute( 'aria-controls' ) ).setAttribute( 'hidden', '' );
}
event.preventDefault();
}
}, false );
}
}() );
Currently I use the function without a loop. This means that the function can still be called after an ajax call.
Furthermore, I want that when a user has selected a field (select or checkbox) that I keep the current accordion open after an ajax request!
Here is a jsfiddle to take a closer look https://jsfiddle.net/5p713cty/1/
Thanks in advance!