2023-04-12 19:37:23 +00:00
|
|
|
/**
|
|
|
|
* Attaches a click event listener to a parent element and calls a callback when one of the child elements,
|
|
|
|
* specified by the list of queries, is clicked. This allows handling events for child elements that may not
|
|
|
|
* exist in the DOM when the event listener is added.
|
|
|
|
*
|
|
|
|
* @param {string} parentQuery query of the parent element.
|
|
|
|
* @param {Array<Object>} children array of event, child query and callback pairs.
|
|
|
|
*/
|
|
|
|
export function attachEventListenerToParentForChildren(
|
|
|
|
parentQuery: string,
|
|
|
|
children: Array< {
|
|
|
|
eventName: 'click' | 'change';
|
|
|
|
childQuery: string;
|
2023-04-17 15:50:30 +00:00
|
|
|
callback: ( clickedElement: Element ) => void;
|
2023-04-12 19:37:23 +00:00
|
|
|
} >
|
|
|
|
) {
|
|
|
|
const parent = document.querySelector( parentQuery );
|
|
|
|
|
|
|
|
if ( ! parent ) return;
|
|
|
|
|
|
|
|
const eventListener = ( event: Event ) => {
|
|
|
|
children.forEach( ( { eventName, childQuery, callback } ) => {
|
|
|
|
if (
|
|
|
|
event.type === eventName &&
|
|
|
|
( event.target as Element ).matches( childQuery )
|
|
|
|
) {
|
2023-04-17 15:50:30 +00:00
|
|
|
callback( event.target as Element );
|
2023-04-12 19:37:23 +00:00
|
|
|
}
|
|
|
|
} );
|
|
|
|
};
|
|
|
|
|
|
|
|
children.forEach( ( { eventName } ) => {
|
|
|
|
parent.addEventListener( eventName, eventListener );
|
|
|
|
} );
|
|
|
|
}
|
|
|
|
|
2022-05-30 13:06:34 +00:00
|
|
|
/**
|
|
|
|
* Recursive function that waits up to 3 seconds until an element is found, then calls the callback.
|
|
|
|
*
|
2022-06-21 08:37:34 +00:00
|
|
|
* @param {string} query query of the element.
|
|
|
|
* @param {Function} func callback called when element is found.
|
|
|
|
* @param {number} tries used internally to limit the number of tries.
|
2022-05-30 13:06:34 +00:00
|
|
|
*/
|
|
|
|
export function waitUntilElementIsPresent(
|
|
|
|
query: string,
|
|
|
|
func: () => void,
|
|
|
|
tries = 0
|
|
|
|
) {
|
|
|
|
if ( tries > 6 ) {
|
|
|
|
return;
|
|
|
|
}
|
|
|
|
setTimeout( () => {
|
|
|
|
const element = document.querySelector( query );
|
|
|
|
if ( element ) {
|
|
|
|
func();
|
|
|
|
} else {
|
|
|
|
waitUntilElementIsPresent( query, func, ++tries );
|
|
|
|
}
|
|
|
|
}, 500 );
|
|
|
|
}
|