🛠️ Popover: Refactor
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.
const 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.
const 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.
const 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.
const getPopoverTrigger = popover => {
return document.querySelector(`.popover-trigger[data-target="${popover.id}"]`)
}
Using it:
const popoverTrigger = getPopoverTrigger(popover.id)
That’s it!