We know a few things so far:
- When we close a User-triggered modal, we need to set the button’s
aria-expandedattribute. - Timed modals don’t have a
buttonElement. We cannot setaria-expandedinsideTimedModal. This means everything regardingbuttonElementshould be moved toUserTriggeredModal. - We used
modal.closeto close the modal. We did this three times with event listeners insideBaseModal. - When we use
modal.closeto close the modal in User-triggered modals, we need to set the button’saria-expandedattribute back tofalse.
I’ll bring you through a process to discover the solution I recommend.
Step 1: Creating event listeners in each derivative modal
When we close User-triggered modals, we need to run an extra buttonElement.setAttribute line. But we don’t have to do this when we close Timed modals. This means there’s a difference in requirements when closing modals.
The easiest way to resolve this difference is to create event listeners inside derivative modals.
function BaseModal(settings) { // ... // Remove these closeButtonElement.addEventListener('click', _ => { modal.close() })
overlayElement.addEventListener('click', event => { if (!event.target.closest('.modal')) { modal.close() } })
document.addEventListener('keydown', event => { if (modal.isOpen && event.key === 'Escape') { modal.close() } })}We copy-paste the event listeners into each derivative modal:
function UserTriggeredModal(settings) { // ... // Paste code here}
function TimedModal(settings) { // ... // Paste code here}For these event listeners to work, we need to declare variables like closeButtonElement and modalOverlay on each derivative modal.
function UserTriggeredModal(settings) { const modal = BaseModal(settings) const { modalElement, buttonElement } = settings const overlayElement = modalElement.parentElement const closeButtonElement = modalElement.querySelector('.jsModalClose')
// Add event listeners}
function TimedModal(settings) { const modal = BaseModal(settings) const { modalElement } = settings const overlayElement = modalElement.parentElement const closeButtonElement = modalElement.querySelector('.jsModalClose')
// Add event listeners}We can set buttonElement’s aria-expanded to false in UserTriggeredModal now.
function UserTriggeredModal(settings) { // ...
closeButtonElement.addEventListener('click', _ => { modal.close() buttonElement.setAttribute('aria-expanded', false) })
overlayElement.addEventListener('click', event => { if (!event.target.closest('.modal')) { modal.close() buttonElement.setAttribute('aria-expanded', false) } })
document.addEventListener('keydown', event => { if (modal.isOpen && event.key === 'Escape') { modal.close() buttonElement.setAttribute('aria-expanded', false) } })}This works, but it a lot of repetition, so it’s not the best solution.
Step 2: Overwriting the close method
If we can overwrite close in UserTriggeredModal, we don’t need to call buttonElement.setAttribute three times (once in each event listener).
We can simply call the close method, like this:
function UserTriggeredModal(settings) { // ...
closeButtonElement.addEventListener('click', _ => { modal.close() })
overlayElement.addEventListener('click', event => { if (!event.target.closest('.modal')) { modal.close() } })
document.addEventListener('keydown', event => { if (modal.isOpen && event.key === 'Escape') { modal.close() } })}Overwriting the method consist of three steps:
- Creating a method with the same name in the derivative class
- Call the parent’s method
- Add any code you wish to add
This process is easy if you used a Class syntax.
// Example for Class syntaxclass BaseModal { // ... close() { /* ...*/ }}
class UserTriggeredModal extends BaseModal { close() { super.close() // Add code here }}The process is tougher with Factory Functions. We need to create an instance of BaseModal first. We’ll name this base instead of modal since we want modal to be the eventual object.
function UserTriggeredModal(settings) { const base = BaseModal(settings)}Then, we need to extend base with another object. Normally we can do this with Object.assign.
function UserTriggeredModal(settings) { const base = BaseModal(settings) const modal = Object.assign({}, base, { /* ... */ })}But we cannot use Object.assign here because we used getter functions. Object.assign doesn’t copy getter functions. It copies the results from a getter function.
We need to use a custom function called mix to merge base with a new object.
Here’s the simple version of mix. There’s also a robust version if you wish to use it. I explained how mix works in this article.
function mix(...sources) { const result = {} for (const source of sources) { const props = Object.keys(source) for (const prop of props) { const descriptor = Object.getOwnPropertyDescriptor(source, prop) Object.defineProperty(result, prop, descriptor) } } return result}We can use mix like Object.assign. The difference is: we don’t need to pass an empty object as the first argument. mix creates this empty object automatically.
function UserTriggeredModal(settings) { const base = BaseModal() const modal = mix(base, { /* ... */ })}We can now overwrite the close method by providing a method with the same name.
function UserTriggeredModal(settings) { const base = BaseModal() const modal = mix(base, { close() { // Overwrites the close method }, })}Then we call the parent’s close method (which is base.close) and add any code we wish. In this case, we’ll add the buttonElement.setAttribute line.
function UserTriggeredModal(settings) { const { modalElement, buttonElement } = settings const base = BaseModal() const modal = mix(base, { close() { base.close() buttonElement.setAttribute('aria-expanded', false) buttonElement.focus() }, })}We can now use modal.close in the three event listeners.
function UserTriggeredModal(settings) { // ...
closeButtonElement.addEventListener('click', _ => { modal.close() })
overlayElement.addEventListener('click', event => { if (!event.target.closest('.modal')) { modal.close() } })
document.addEventListener('keydown', event => { if (modal.isOpen && event.key === 'Escape') { modal.close() } })}Since we overwrote close in UserTriggredModal, it makes sense to overwrite open too.
function UserTriggeredModal(settings) { // Declare variables
const modal = mix(base, { open() { base.open() buttonElement.setAttribute('aria-expanded', true) }, // Other methods })
buttonElement.addEventListener('click', _ => { modal.open() })
// Other event listeners}Step 3: Adding the event listeners inside Modal
We’ve reduced the amount of code by overwriting the close method in UserTriggeredModal. But there’s still a lot of duplication between UserTriggeredModal and TimedModal.
We can reduce code duplication by deferring the adding of common event listeners after the derivative modals are created. The easiest way is to add event listeners inside Modal instead of derivative modals.
To do this, we need to return the modal in each derivative modal.
function UserTriggeredModal(settings) { // ... return modal}
function TimedModal(settings) { // ... return modal}We then add event listeners in Modal instead of the derivative modals. You can remove these three event listeners from UserTriggeredModal and TimedModal at this point.
export default function Modal(settings) { settings = Object.assign({}, defaults, settings)
const { type } = settings let modal
// Create Modal switch (type) { case 'normal': modal = UserTriggeredModal(settings) break case 'timed': modal = TimedModal(settings) break }
// Adds event listeners const { modalElement } = settings const overlayElement = modalElement.parentElement const closeButtonElement = modalElement.querySelector('.jsModalClose')
closeButtonElement.addEventListener('click', _ => { modal.close() })
overlayElement.addEventListener('click', event => { if (!event.target.closest('.modal')) { modal.close() } })
document.addEventListener('keydown', event => { if (modal.isOpen && event.key === 'Escape') { modal.close() } })}That’s it!
Bonus
Building other components can be frustrating when you have a Timed Modal on screen. This is because the Timed Modal pops up when you don’t want it to.
An easy way to “fix” this is to create the Timed Modal when a button is clicked.
const timedModalButton = document.querySelector('#timed-modal-button')
timedModalButton.addEventListener('click', _ => { Modal({ type: 'timed' delayBeforeOpening: 1000, modalElement: document.querySelector('#time-modal') })})This is just a neat trick to use for development 😉.
Bonus 2
Try extending this Modal to include a Scroll-based modal and an Exit Intent modal. These shouldn’t be too hard for you at this point. (You might have to google around to figure out how to build an Exit Intent Modal though).
Good luck!
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