BigW Consortium Gitlab

toggler_behavior.js 1.33 KB
Newer Older
1 2 3 4 5 6 7
// Toggle button. Show/hide content inside parent container.
// Button does not change visibility. If button has icon - it changes chevron style.
//
// %div.js-toggle-container
//   %button.js-toggle-button
//   %div.js-toggle-content
//
8
import { getLocationHash } from '../lib/utils/url_utility';
9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24

$(() => {
  function toggleContainer(container, toggleState) {
    const $container = $(container);

    $container
      .find('.js-toggle-button .fa')
      .toggleClass('fa-chevron-up', toggleState)
      .toggleClass('fa-chevron-down', toggleState !== undefined ? !toggleState : undefined);

    $container
      .find('.js-toggle-content')
      .toggle(toggleState);
  }

  $('body').on('click', '.js-toggle-button', function toggleButton(e) {
25
    e.target.classList.toggle('open');
26 27 28 29 30
    toggleContainer($(this).closest('.js-toggle-container'));

    const targetTag = e.currentTarget.tagName.toLowerCase();
    if (targetTag === 'a' || targetTag === 'button') {
      e.preventDefault();
31 32
    }
  });
33 34 35

  // If we're accessing a permalink, ensure it is not inside a
  // closed js-toggle-container!
36
  const hash = getLocationHash();
37 38 39 40 41 42 43 44
  const anchor = hash && document.getElementById(hash);
  const container = anchor && $(anchor).closest('.js-toggle-container');

  if (container) {
    toggleContainer(container, true);
    anchor.scrollIntoView();
  }
});