I have a set of Accordion(s) (better say, a set of expandable sections in a single page), each of one could be identified by a custom ID (as side note, is a Liferay 7.4 custom fragment).
I'd need to manage open/close of them not only when their headings are clicked but also in case that in URL is passed an anchor after the friendlyURL.
I created a specific function that act on each element to manage open/close, and I'd need to trigger it in two cases, obviously on accordion heading click and also comparing the eventual anchor in URL and the corresponding accordion id.
Here a simplified version of my jQuery code, the function is binded at accordion heading click:
$('.accordion-heading').on('click',toggleOpen);
function toggleOpen(){
if( $(this).attr('aria-expanded') == 'false' ) {
$(this).attr('aria-expanded','true');
$(this).next().removeClass('hide');
}
else if( $(this).attr('aria-expanded') == 'true' ) {
$(this).attr('aria-expanded','false');
$(this).next().addClass('hide');
}
}
In this case, $(this) selector is perfect for my needs.
I tried to add logic to manage also the url anchor auto-open, in the following way:
const targetAnchor = $(location).attr('hash');
const thisAnchor = configuration.anchor; // value taken by fragment configuration is a simple string
if( (targetAnchor.replace('#','')) == thisAnchor) {
let thisAccordionHeading = $(targetAnchor).find('.accordion-heading');
console.log($(thisAccordionHeading)); // Verify that target item is correctly found
// ---- execute "toggleOpen" function on this specific item
}
In this case, I sincerely don't know how to execute the same function to the $(thisAccordionHeading) preserving the logic