Untitled

mail@pastecode.io avatar
unknown
plain_text
a month ago
2.2 kB
2
Indexable
Never
selectDropdownOption(e, block) {
    e.stopPropagation();
    const selected = e.target.getAttribute('value');
    const dropdownButton = block.querySelector('.dropdown-button');
    const target = block.querySelector(`.performance-data-${selected}`);
    const items = Array.from(block.querySelectorAll('.performance-data__item'));
    const dropdownOptions = Array.from(block.querySelectorAll('.dropdown-option'));

    // Remove previously selected class
    dropdownOptions.forEach(option => option.classList.remove('selected'));

    // Mark the current selected option
    e.target.classList.add('selected');

    if (dropdownButton) {
        dropdownButton.innerText = e.target.innerText;
    }

    items.forEach(item => item.setAttribute('aria-selected', false));

    if (target) {
        target.setAttribute('aria-selected', true);
    }

    this.closeDropdown(block);

    assignEventAction(e);
}

// Call this function on initialization to set the tick mark based on priority
initializeSelectedState(dropdownOptions, dropdownButton) {
    const hashValue = window.location.hash ? window.location.hash.replace('#', '').toLowerCase() : null;
    let selectedOption = null;

    if (hashValue) {
        selectedOption = dropdownOptions.find(option => option.getAttribute('value') === hashValue);
    }

    if (!selectedOption && this.selectedState) {
        selectedOption = dropdownOptions.find(option => {
            const defaultInStates = option.dataset.defaultInStates?.split(' ');
            return defaultInStates && defaultInStates.includes(this.selectedState);
        });
    }

    if (!selectedOption) {
        selectedOption = dropdownOptions[0];
    }

    if (selectedOption && dropdownButton) {
        dropdownButton.innerText = selectedOption.innerText;
        selectedOption.classList.add('selected');
    }
}

// Make sure to call `initializeSelectedState` in your initBlock method
initBlock(block) {
    const dropdownOptions = Array.from(block.querySelectorAll('.dropdown-option'));
    const dropdownButton = block.querySelector('.dropdown-button');

    // Existing code...

    this.initializeSelectedState(dropdownOptions, dropdownButton);
}
Leave a Comment