Implementing Modal Functionality
In this lesson, we will use JavaScript to implement a modal functionality.
- Select Modal DOM Elements:
const modal = document.getElementById('modal');
const modalClose = document.getElementsByClassName('modal-close')[0];
- Get references to the entire modal and the close button.
- Show Modal on Image Click:
function gridImageClick() {
modal.style.display = 'block';
}
- The
gridImageClick
function is called when an image with the class.grid-image
is clicked, and it displays the modal.
- Hide Modal on Close Button Click:
modalClose.onclick = function () {
modal.style.display = 'none';
};
- Hides the modal when the close button is clicked.
- Hide Modal on External Click:
window.onclick = function (event) {
if (event.target == modal) {
modal.style.display = 'none';
}
};
- This event listener is triggered whenever the page is clicked, and if the clicked target is the modal background, it hides the modal.
- Add Click Event Listeners to Each Image:
document.querySelectorAll('.grid-image').forEach(function (el) {
el.addEventListener('click', (e) => {
const gridImage = e.target;
const gridImageInString = gridImage.outerHTML;
const alt = gridImage.alt;
const modalImage = document.getElementById('modal-image');
const modalText = document.getElementById('modal-text');
modalImage.innerHTML = gridImageInString;
modalText.innerHTML = alt;
});
});
-
Add click event listeners to all elements with the
.grid-image
class. -
When an image is clicked, its HTML and
alt
attribute are retrieved and set to the respective image and text areas inside the modal. This allows the clicked image and its description (alt attribute) to be displayed in the modal.
Want to learn more?
Join CodeFriends Plus membership or enroll in a course to start your journey.