W04 Learning Activity: Modals
Overview
A modal is a window that opens on top of the page and must be dismissed before the user can continue. Modals are used for details, confirmations, and prompts.
In this activity, you will build, script, and style one.
Prepare
A modal dialog is built using the dialog element. It is a block-level element that can be styled with CSS and can be controlled with JavaScript.
A dialog is hidden until you open it. The showModal() method opens it as a modal: it sits above the page, shows a backdrop, and closes with the Esc key. The show() method opens it as a non-modal dialog. The close() method hides it again. Avoid setting the open attribute yourself.
The following is an example of how to create a modal dialog using the dialog element:
<dialog id="myModal">
<h2>Modal Dialog</h2>
<p>This is a modal dialog.</p>
<button id="closeModal">Close</button>
</dialog>
In this example, the dialog element is used to create a modal dialog with a title and a close button. The id attribute is used to identify the dialog so that it can be controlled with JavaScript.
This dialog element will not be visible until the showModal() method is called in JavaScript, so do not worry if you start a test page with this HTML and nothing shows up.
To style the modal dialog, you can use CSS to set the width, height, background color, and other properties of the dialog element. You can also use the ::backdrop pseudo-element to style the background of the modal dialog.
The following is an example of how to style a modal dialog using CSS:
dialog {
width: min(90%, 400px);
background-color: white;
border: 1px solid black;
border-radius: 5px;
box-shadow: 0 0 10px rgb(0 0 0 / 50%);
padding: 20px;
}
dialog::backdrop {
background-color: rgb(0 0 0 / 50%);
}
In this example, the dialog element is styled with a width that fits small screens, a white background color, a black border, and a box shadow. The ::backdrop pseudo-element is used to style the background of the modal dialog with a semi-transparent black color.
To control the modal dialog with JavaScript, you can use the showModal() and close() methods to display and hide the modal dialog. You can also use the addEventListener() method to add event listeners to the modal dialog and its elements.
The following is an example of how to control a modal dialog using JavaScript:
const modal = document.querySelector('#myModal');
const closeModal = document.querySelector('#closeModal');
modal.showModal(); // display the modal dialog right away.
// Usually you will want to wait for a user action to show the modal dialog
closeModal.addEventListener('click', () => {
modal.close();
});
In this example, the showModal() method is used to display the modal dialog, and the close() method is used to hide the modal dialog when the close button is clicked. The addEventListener() method is used to add a click event listener to the close button.
The following CodePen project demonstrates two ways to employ modal dialogs:
- The first example uses the
<dialog>element with accompanying JavaScript support as demonstrated in the code examples above. - The second example uses the
popoverattribute (<dialog popover>) as an alternative way to show overlays or 'popups' on a page. It needs no JavaScript:popovertargeton the "Sign Up" button opens it, andpopovertargetaction="hide"on the ❌ button closes it. Note that a popover is not modal. The rest of the page stays interactive.
Code Example: Modals using dialog and ::backdropExample using an HTML dialog, :modal pseudo-class, and ::backdrop pseudo-element
Activity Instructions
Using your course home page, enable modal behavior by responding to users clicking on a course card/button and displaying details about the course.
The following video is an example of the action and display effect.
HTML
- Open your course home page.
- Add an empty
dialogelement. Add it just before the closing</main>tag.
Check Your Understanding – Example
<dialog id="course-details"></dialog>
CSS
Use existing style patterns that you have developed and note that any additional CSS should support your design scheme overall.
- Use
dialogto style the modal container.The selector
dialog:modalmatches only while the dialog is open as a modal.
It is recommended that you style thedialogor you can assign anidorclassto thedialogand use that selector. - Use
dialog::backdropto style the area behind the modal. - Style the close
buttonthat you add to thedialog.
Check Your Understanding – Example
dialog {
border: 1px solid rgb(0 0 0 / 10%);
border-radius: .25rem;
padding: 1rem;
background-color: #fff;
box-shadow: 0 0 3rem #777;
width: 90%;
max-width: 600px;
}
dialog::backdrop {
background-color: rgb(0 0 0 / 50%);
}
dialog button {
position: absolute;
top: 23px;
right: 23px;
padding: .5rem 1rem;
border: 1px solid rgb(0 0 0 / 10%);
}
JavaScript
- Write a function to display the modal.
- Add the following content to the modal display:
- subject and number
- title
- credits
- description
- certificate
- technology stack
- a button that will close the modal
- an event listener to close the modal when the user clicks outside of the modal
Check Your Understanding – Example
This example assumes that you have declared and initialized the
courseDetailsvariable to reference the HTMLdialogelement.function displayCourseDetails(course) { courseDetails.innerHTML = ` <button id="closeModal" aria-label="Close">❌</button> <h2>${course.subject} ${course.number}</h2> <h3>${course.title}</h3> <p><strong>Credits</strong>: ${course.credits}</p> <p><strong>Certificate</strong>: ${course.certificate}</p> <p>${course.description}</p> <p><strong>Technologies</strong>: ${course.technology.join(', ')}</p> `; courseDetails.showModal(); courseDetails.querySelector('#closeModal').addEventListener('click', () => { courseDetails.close(); }); } // Close the modal when the user clicks outside of it (on the backdrop) courseDetails.addEventListener('click', (event) => { if (event.target === courseDetails) { courseDetails.close(); } }); - Add a 'click' event listener to each course card as you build it (inside the loop building each course card). This trigger will call the new display function, passing the current course's information.
Check Your Understanding
courseCard.addEventListener('click', () => { displayCourseDetails(course); });Make each course card a
<button>element instead of adiv. A button can be reached and activated with the keyboard. Adivcannot.
Coding Demonstration Videos
For those who prefer to watch and learn, there is a video lab on modal dialogs. The first video covers building a single modal. The second video builds on the first and shows you how to reuse a dialog for multiple popups. The third video shows how to build modals from a JSON file and also includes JavaScript Modules with import / export. This series should help you complete the Modal Dialog assignment for this week.
These labs are designed so that you can follow along and learn. You will need to pause the video instruction as you code your own project.
Download a start lab folder for the first video.
Watch Modal Dialog Part 1 Single Dialog Example
Watch Modal Dialog Part 2 Reusable Dialog
Download a start lab folder with the temple data.
Watch Modal Dialog Part 3 Scripted Dialog with JSON Temple Data A
Watch Modal Dialog Part 4 Scripted Dialog with JSON Temple Data B
Optional Resources
- HTML
dialogelement – MDN :modalCSS Pseudo-class – MDN