Created
March 17, 2024 15:04
-
-
Save jasondmoss/c374159c8cda1e380d1708095916007e to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* @file | |
* | |
* Module: Toggle. | |
* | |
* @author Jason D. Moss <[email protected]> | |
* @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