Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

fix(donate): reset "other" value when switching tiers #1549

Merged
merged 2 commits into from
Oct 10, 2023
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
60 changes: 60 additions & 0 deletions src/blocks/donate/frequency-based/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,3 +2,63 @@
* Internal dependencies
*/
import './style.scss';

/**
* Specify a function to execute when the DOM is fully loaded.
*
* @see https://github.com/WordPress/gutenberg/blob/trunk/packages/dom-ready/
*
* @param {Function} callback A function to execute after the DOM is ready.
* @return {void}
*/
function domReady( callback: () => void ): void {
if ( typeof document === 'undefined' ) {
return;
}
if (
document.readyState === 'complete' || // DOMContentLoaded + Images/Styles/etc loaded, so we call directly.
document.readyState === 'interactive' // DOMContentLoaded fires at this point, so we call directly.
) {
return void callback();
}
// DOMContentLoaded has not fired yet, delay callback until then.
document.addEventListener( 'DOMContentLoaded', callback );
}

const resetOtherValue = ( container: HTMLElement ) => {
const frequencies = container.querySelectorAll( '.tiers' );
if ( ! frequencies?.length ) {
return;
}
const frequencyInputs = container.querySelectorAll( 'input[name="donation_frequency"]' );
frequencies.forEach( frequency => {
const tiers = frequency.querySelectorAll( 'input[type="radio"]' );
const input = <HTMLInputElement>frequency.querySelector( '.money-input input' );
if ( ! tiers?.length || ! input ) {
return;
}
const originalValue = input.getAttribute( 'value' );
const reset = () => {
input.value = originalValue || '';
};
tiers.forEach( tierInput => {
tierInput.addEventListener( 'change', reset );
} );
frequencyInputs.forEach( frequencyInput => {
frequencyInput.addEventListener( 'change', reset );
} );
} );
};

export const processFrequencyBasedElements = ( parentEl = document ) => {
const elements = parentEl.querySelectorAll(
'.wpbnbd--frequency-based'
) as NodeListOf< HTMLElement >;
elements.forEach( container => {
resetOtherValue( container );
} );
};

if ( typeof window !== 'undefined' ) {
domReady( () => processFrequencyBasedElements() );
}