Skip to content

Recipes

Ryan Domingue edited this page May 3, 2020 · 4 revisions

React to hashchange events

There are times when authors will need to activate a component based on hash changes, such as when sharing a URL to a specific FAQ item.

Tablist Example

https://goodguyry.github.io/AriaComponents/#second-panel

window.addEventListener('load', tablistHashCheck);
window.addEventListener('hashchange', tablistHashCheck);

/**
 * Check for a hash in the URL and activate the corresponding panel.
 */
function tablistHashCheck() {
  const hash = window.location.hash.replace('#', '');
  const el = document.getElementById(hash);

  if (null !== el && el.tablist instanceof Tablist) {
    const { tablist } = el;
    const index = tablist.panels.indexOf(el);

    if (-1 < index) {
      tablist.switchTo(index);
      el.scrollIntoView({ behavior: 'smooth' });
    }
  }
}

Disclosure Example

https://goodguyry.github.io/AriaComponents/#markup-options

window.addEventListener('load', disclosureHashCheck);
window.addEventListener('hashchange', disclosureHashCheck);

/**
 * Check for a hash in the URL and open the corresponding disclosure.
 */
function disclosureHashCheck() {
  const hash = window.location.hash.replace('#', '');
  const el = document.getElementById(hash);

  if (null !== el && el.disclosure instanceof Disclosure) {
    const { disclosure } = el;
    disclosure.open();
    disclosure.controller.scrollIntoView({ behavior: 'smooth' });
  }
}
Clone this wiki locally