We wrote pretty good code so far. We can improve it by creating a few functions to make it easier to understand.
Hiding the popover
We used setAttribute to hide the popover in many parts of the code. Hereβs an example:
popoverTriggers.forEach(popoverTrigger => { // ... popover.setAttribute('hidden', true)})We can create a hidePopover function to hide the popover.
function hidePopover(popover) { popover.setAttribute('hidden', true)}Weβll use it like this:
hidePopover(popover)Showing the popover
Since we used hidePopover to hide the popover, it makes sense to create a showPopover to show the popover.
function showPopover(popover) { popover.removeAttribute('hidden')}Weβll use it like this:
showPopover(popover)Getting focusable elements
We used this to get keyboard focusable elements:
const focusables = [ ...popover.querySelectorAll( 'a, button, input, textarea, select, [tabindex]:not([tabindex="-1"])', ),]This code can be difficult to parse through. We can create a function called getKeyboardFocusableElements to hold it.
function getKeyboardFocusableElements(element) { return [ ...element.querySelectorAll( 'a, button, input, textarea, select, [tabindex]:not([tabindex="-1"])', ), ]}Using it:
const focusables = getKeyboardFocusableElements(popover)Getting the popover trigger
We used this code to get the popover trigger twice:
const popoverTrigger = document.querySelector( `.popover-trigger[data-target="${popover.id}"]`,)We can put this into a function to make it easier to understand.
function getPopoverTrigger(popover) { return document.querySelector(`.popover-trigger[data-target="${popover.id}"]`)}Using it:
const popoverTrigger = getPopoverTrigger(popover.id)Thatβs it!
Welcome! Unfortunately, you donβt have access to this lesson. To get access, please purchase the course or enroll in Magical Dev School.
Unlock this lesson