Skip to content

Browser JavaScript

Sub-resource integrity

<script src="//cdnjs....."
 integrity="sha256-..."
crossorigin="anonymous">

if the CDN gets hacked, then the script won't run

Get the URL params

// ?q=turtles or window.location.search
search_string = new URL("https://www.google.ca/search?q=turtles&oq=tortuga");
search_string = new URL(window.location.search);

params = new URLSearchParams(search_string);

params.get("q"); // "turtles"
const { q } = Object.fromEntries(params);

!!! Note: Object.fromEntries only works for regular keys

JS Event Handler

Keyboard event

Spacebar vs Enter

  • spacebar: trigger event on keyup
  • enter: trigger on keydown

https://www.clairecodes.com/blog/2019-11-06-the-roles-of-spacebar-and-enter-in-keyboard-navigation/

Key Expected functions
Spacebar
  • activate buttons
  • check/uncheck checkbox
  • scroll down the page
  • expand a dropdown menu
Enter
  • activate buttons
  • open links
  • open menus
Element to access Key
Link - Enter
Button - Enter
- Spacebar

Don't need generics because we aren't using custom properties of an HTMLInputElement for example

buttonA11yProps.ts
const triggerClickOnKeyboardEvent =
    (triggerKeys: string[]) => (e: React.KeyboardEvent<HTMLElement>) => {
        if (triggerKeys.includes(e.key)) {
            e.preventDefault();
            e.target.click();
        }
    };

export const triggerClickOnEnterKey = triggerClickOnKeyboardEvent(["Enter"]);
export const triggerClickOnSpacebar = triggerClickOnKeyboardEvent([" "]);

/**
 * @example
 * <div
 *    onClick={() => {})}
 *    {...clickOnEnterOrSpacebarProps}
 *    className="clickable other-classes"
 * />
 * >
 *
 * @example
 * <div
 *    onClick={() => {})}
 *    {...clickOnEnterOrSpacebarProps}
 *    onKeyDown={() => { console.log('Custom onKeyDown')}}
 * />
 */
export const clickOnEnterOrSpacebarProps = {
    role: "button",
    className: "clickable",
    tabIndex: 0,
    onKeyDown: triggerClickOnEnterKey,
    onKeyUp: triggerClickOnSpacebar,
};

Last update: 2022-09-23