Skip to content

Instantly share code, notes, and snippets.

@jasondmoss
Created March 17, 2024 15:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save jasondmoss/c374159c8cda1e380d1708095916007e to your computer and use it in GitHub Desktop.
Save jasondmoss/c374159c8cda1e380d1708095916007e to your computer and use it in GitHub Desktop.
/**
* @file
*
* Module: Toggle.
*
* @author Jason D. Moss <jason@jdmlabs.com>
* @copyright 2024 Jason D. Moss. All rights reserved.
*/
import { Exists } from "./exists.js";
export class Toggler {
constructor (event) {
this.event = event;
this.element = this.event.target;
this.key = this.event.key;
}
/**
* Toggle ARIA 'expanded' state.
*/
toggleARIAState (toggle) {
let expandedState = toggle.getAttribute("aria-expanded");
if (new Exists(expandedState)) {
toggle.setAttribute("aria-expanded", (
expandedState === "false" ?? "true"
));
}
}
/**
* Toggle 'hidden' attribute on target element.
*/
toggleButton () {
this.toggleARIAState(this.element);
// Toggle visibility.
let targetElem = document.getElementById(
this.element.getAttribute("aria-controls")
);
if (new Exists(targetElem)) {
targetElem.toggleAttribute("hidden");
targetElem.scrollIntoView();
}
}
/**
* Handle button toggle 'click' action,
*/
handleClick () {
this.event.preventDefault();
this.toggleButton(this.element);
}
/**
* Handle button toggle 'key' action,
*/
handleKeyboard () {
this.event.preventDefault();
if (this.key === " " ||
this.key === "Enter" ||
this.key === "Spacebar"
) {
this.toggleButton(this.element);
}
}
}
/* <> */
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment